簡體   English   中英

FileWriter()僅會追加,不會覆蓋

[英]FileWriter() will only append, not overwrite

我有一個應該用新內容覆蓋當前文件的方法,但是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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM