Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a .dat file in java

Tags:

java

file

file-io

I want to create a .dat file in java which doesn't exist. I don't know how to manually create it either. I know that the following code:

 File f = new File(file); 

is used for the file, but what exactly is the code for a file which doesn't exist. In other words create a new file.

like image 463
h-rai Avatar asked Dec 15 '22 20:12

h-rai


1 Answers

A statement like File f = new File(file); will not create a file on disk. Class java.io.File only represents a file path, not the actual file on disk.

To create a new file, open a FileOutputStream for it, which you can then use to write data to the file.

OutputStream out = new FileOutputStream("C:\\Temp\\filename.dat");
try {
    // Write data to 'out'
} finally {
    // Make sure to close the file when done
    out.close();
}
like image 99
Jesper Avatar answered Dec 29 '22 15:12

Jesper