Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java overwriting an existing output file

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.

like image 358
john stamos Avatar asked Jul 30 '13 21:07

john stamos


People also ask

How do you overwrite a file if it already exists in Java?

write("some text"); It will create a file abc. txt if it doesn't exist. If it does, it will overwrite the file.

How do I overwrite a file?

Overwriting a File, Part 1 To edit the settings for a file, locate the file you wish to overwrite and hover over the file name. Click the chevron button that appears to the right of the file name and select Overwrite File from the menu.

How do I append a file with FileOutputStream?

Using FileOutputStream FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter . To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .


2 Answers

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);
like image 96
Sam I am says Reinstate Monica Avatar answered Sep 22 '22 06:09

Sam I am says Reinstate Monica


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.

like image 29
Rohit Jain Avatar answered Sep 21 '22 06:09

Rohit Jain