FileWriter() will only append, not overwrite

1k views Asked by At

I have a method that is supposed to overwrite the current file with new content, however the FileWriter() is only appending the new content, not overwriting the old content.

This is how my FileWriter is set up

File file = new File(test.txt);
BufferedWriter out;
out = new BufferedWriter(new FileWriter(file, false));

Here is the save method

//stuff is defined earlier and filled with the new content for the file
ArrayList<String> stuff = new ArrayList<>();

//The actual save() method
Object[] lines = stuff.toArray();
for (Object item : lines) {
    out.write(item.toString());
    out.newLine();
}
out.flush();

The problem happens when I run this method, instead of overwriting the file, it appends the new content to the file.

What I want:

line 1
line 2
line 3 <--------- This is added when the file is overwritten

What Happens:

line 1
line 2
line 1 --|
line 2   |------ This was all re-appended to the original 1st 2 lines
line 3 --|
1

There are 1 answers

0
Dennis Simpson On

I know this is an old question but I had the same problem recently. You need to clear your ArrayList that contains the output data otherwise the new data will simply append to the old. I use StringBuilder:

    StringBuilder moduleData = new StringBuilder();
    moduleData.append("--target_perm_group_size\t").append(targetGroupSize).append("\n");
    moduleData.append("--prog_check\t").append(progCheck).append("\n");

    FileSaveUtility.fileSaveWindow(moduleData.toString());
    moduleData.setLength(0);