20

My program is currently using

FileOutputStream output = new FileOutputStream("output", true);

A while loop creates the output file if it is not yet created and appends some data to this file for every iteration of the while loop using

 output.write(data).  

This is fine and is what I want.

If I run the program again the file just doubles in size as it appends the exact information to the end of the file. This is not what I want. I would like to overwrite the file if I run the program again.

john stamos
  • 1,054
  • 5
  • 17
  • 36

3 Answers3

33

This documentation suggests that the parameter you're passing is the append parameter.

the signature looks like the following

FileOutputStream(File file, boolean append)

You should set that parameter to false since you don't want to append.

FileOutputStream output = new FileOutputStream("output", false);
17

I would like to overwrite the file if I run the program again.

Pass false as 2nd argument, to set append to false:

FileOutputStream output = new FileOutputStream("output", false);

Check out the constructor documentation:

If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • This works. I'm not sure why though. I thought changing that to false would continually overwrite my loop data rather than the whole file which would be bad. If you feel like explaining that would be awesome but no big deal. But yes that worked, thank you. – john stamos Jul 30 '13 at 21:43
  • 1
    You open a file in either append mode or write mode. After that whatever you write to the file, will be done accordingly. Mode is specified only while opening a file. If you want to append next time, you would need to close the file, and re-open it in append mode. – Rohit Jain Jul 30 '13 at 21:46
  • 4
    the default value there is `false` – YTerle Apr 15 '18 at 21:08
1

Or you could just delete the file if it's there, and then always create it and job done.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39