0

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 --|
5
  • 1
    Why use anything File in 2015? Why don't you use Files.newBufferedWriter() with options StandardOpenOption.{TRUNCATE_EXISTING,APPEND}?
    – fge
    Jun 9, 2015 at 17:45
  • And while we're at it, you might want to take a look at the whole nio package
    – Turing85
    Jun 9, 2015 at 17:48
  • Dumb question but are you ever closing the FileWriter? Unclosed streams cause all sorts of bazaar behavior.
    – initramfs
    Jun 9, 2015 at 18:15
  • Why use anything File in 2015? Why not when it is still working. Jun 9, 2015 at 19:01
  • FileWriter behaves exactly as described in the Javadoc. Your problem lies elsewhere. Are you clearing the ArrayList?
    – user207421
    Mar 30, 2022 at 9:54

1 Answer 1

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.