2

I have a file that contains only a very small amount of information that needs to be updated periodically. In other words, I want to truncate the file before writing to it. The easiest solution I found was to delete and create it again as shown here:

File myFile = new File("path/to/myFile.txt");
myFile.delete();
myFile.createNewFile();
// write new contents

This 'works' fine, but is there a better way?

JoeG
  • 7,191
  • 10
  • 60
  • 105

2 Answers2

4

There is no need to delete the file and recreate one. If you are writing to the file, for instance using PrintWriter, it will overwrite your current file content.

Example:

 public static void main(String[] args) throws IOException
 {
      PrintWriter prw= new PrintWriter (“MyFile.txt”);
      prw.println("These text will replace all your file content");          
      prw.close();
 }

It will only append to the end of the file if you use the overloaded version of the PrintWriter constructor:

PrintWriter prw= new PrintWriter (new FileOutputStream(new File("MyFile.txt"), true));
//true: set append mode to true
user3437460
  • 17,253
  • 15
  • 58
  • 106
0

In the below example, the "false" causes the file to be overwritten, true would cause the opposite.

File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close(); 
U.Swap
  • 1,921
  • 4
  • 23
  • 41