[英]Java FileWriter with append mode
我目前正在使用FileWriter
來創建和寫入文件。 有什么方法可以讓我每次都寫入同一個文件而不刪除其中的內容?
fout = new FileWriter(
"Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt");
fileout = new PrintWriter(fout,true);
fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");
fileout.close();
在Javadoc中,您可以使用構造函數來指定是否要追加。
公共 FileWriter(文件文件,布爾附加)拋出 IOException
在給定 File 對象的情況下構造一個 FileWriter 對象。 如果第二個參數為真,那么字節將被寫入文件的末尾而不是開頭。
您可以通過傳遞true
作為第二個參數以附加模式打開 FileWriter:
fout = new FileWriter("Distribution_" + ... + ".txt", true);
您可以將 true 作為第二個參數傳遞給 FileWriter 的構造函數,以指示編寫器追加數據而不是重寫文件。
例如,
fout = new FileWriter("Distribution_" + Double.toString( lowerBound) + " " + Double.toString(_highBound) + ".txt", true );
希望這能解決你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.