How to create a .dat file in java

I want to create a .dat file in java that does not exist. I do not know how to do this manually. File f = new file (file); this is the code used for the file, but what is the code for the file that is not there. In other words, create a new file.

+4
source share
4 answers

An operator of type File f = new File(file); does not create a file on disk. The java.io.File class represents only the path to the file, not the actual file on disk.

To create a new file, open 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(); } 
+7
source

Pretty simple:

 File myFile = new File("your_file.bat"); myFile.createNewFile(); 
+3
source

The question is a bit unclear, but this will create a new empty file:

  new File("x.dat").createNewFile(); 

If you want to have some data in it, use FileOutputStream for the file (which will also create it if it is missing, overwrite it if it already exists).

+1
source

Before creating a file, you should also check if this really does not exist.

 File file = new File("abc.dat"); if(!file.exists()) { boolean created = file.createNewFile(); } 
0
source

All Articles