问题描述
我有一个方法应该用新内容覆盖当前文件,但是FileWriter()只是附加新内容,而不是覆盖旧内容。
这就是我的FileWriter设置的方式
File file =新的文件(test.txt);
BufferedWriter出来;
out = new BufferedWriter(new FileWriter(file,false));
这里是保存方法
<$ p $填充文件的新内容
ArrayList< String> stuff = new ArrayList<>();
//实际的save()方法
Object [] lines = stuff.toArray();
for(Object item:lines){
out.write(item.toString());
out.newLine();
}
out.flush();
当我运行这个方法而不是覆盖文件时,会发生这个问题,
我想要的:
第1行
第2行
第3行
$ b $
$ b <$ p
$ b $ 1 $ - - |
line 2 | ------这是全部重新追加到原来的第2行
第3行 - |
我知道这是一个老问题,同样的问题最近。您需要清除包含输出数据的ArrayList,否则新数据将简单地附加到旧数据。我使用StringBuilder:
$ $ p $ StringBuilder moduleData = new StringBuilder();
moduleData.append( - target_perm_group_size\t)。append(targetGroupSize).append(\\\
);
moduleData.append( - prog_check \t)。append(progCheck).append(\\\
);
FileSaveUtility.fileSaveWindow(moduleData.toString());
moduleData.setLength(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 --|
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);
这篇关于FileWriter()只能追加,不能覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!