Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java create a new file, or, override the existing file

Tags:

java

file

What I want to achieve is to create a file regardless of whether the file exists or not.

I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?

Or is there a clearer way of doing it?

like image 626
Terence Lyu Avatar asked Sep 30 '18 19:09

Terence Lyu


People also ask

How do I override an existing file?

If you are accustomed to selecting "File -> Save As" when saving documents, you can also overwrite the file with your changes this way. Select "Replace File. This is the same behavior as File Save." The original file will be overwritten.

How do you create a new file in Java?

java. io. File class can be used to create a new File in Java. When we initialize File object, we provide the file name and then we can call createNewFile() method to create new file in Java.

Does Fileoutputstream overwrite existing file?

Yes it can overwrite to an already existing file.


1 Answers

FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:

Writer fileWriter = new FileWriter("c:\\data\\output.txt", true);  //appends to file

Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
like image 72
Bruno Caceiro Avatar answered Nov 14 '22 23:11

Bruno Caceiro