Java overwriting an existing output file

john stamos picture john stamos · Jul 30, 2013 · Viewed 44.3k times · Source

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.

Answer

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);