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?
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.
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.
Yes it can overwrite to an already existing file.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With