You have successfully created an instance of the class File
, which is very different from creating actual files in your hard drive.
Instances of the File
class are used to refer to files on the disk. You can use them to many things, for instance:
- check if files or directories exist;
- create/delete/rename files or directories; and
- open "streams" to write data into the files.
To create a file in your hard disk and write some data to it, you could use, for instance, FileOutputStream
.
public class AnExample {
public static void main(String... args) throws Throwable {
final File file = new File("file.dat");
try (FileOutputStream fos = new FileOutputStream(file);
DataOutputStream out = new DataOutputStream(fos)) {
out.writeInt(42);
}
}
}
Here, fos
in an instance of FileOutputStream
, which is an OutputStream
that writes all bytes written to it to an underlying file on disk.
Then, I create an instance of DataOutputStream
around that FileOutputStream
: this way, we can write more complex data types than bytes and byte arrays (which is your only possibility using the FileOutputStream
directly).
Finally, four bytes of data are written to the file: the four bytes representing the integer 42
. Note that, if you open this file on a text editor, you will see garbage, since the code above did not write the characters '4' and '2'.
Another possibility would have been to use an OutputStreamWriter
, which would give you an instance of Writer
that can be used to write text (non-binary) files:
public class AnExample {
public static void main(String... args) throws Throwable {
final File file = new File("file.txt");
try (FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
out.write("You can read this with a text editor.");
}
}
}
Here, you can open the file file.txt
on a text editor and read the message written to it.