FileWriter() will only append, not overwrite

僤鯓⒐⒋嵵緔 提交于 2020-01-15 12:24:28

问题


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:


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


来源:https://stackoverflow.com/questions/30739195/filewriter-will-only-append-not-overwrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!