我有一个方法应该用新内容覆盖当前文件,但是 FileWriter() 仅附加新内容,而不覆盖旧内容。
这就是我的 FileWriter 的设置方式
File file = new File(test.txt);
BufferedWriter out;
out = new BufferedWriter(new FileWriter(file, false));
这是保存方法
//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();
当我运行此方法时,问题发生了,它不是覆盖文件,而是将新内容附加到文件中。
我想要什么:
line 1
line 2
line 3 <--------- This is added when the file is overwritten
发生了什么:
line 1
line 2
line 1 --|
line 2 |------ This was all re-appended to the original 1st 2 lines
line 3 --|
最佳答案
我知道这是一个老问题,但我最近遇到了同样的问题。您需要清除包含输出数据的 ArrayList,否则新数据将简单地附加到旧数据。我使用 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);
关于java - FileWriter() 只会追加,不会覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30739195/