在 Java 開發中,將資料寫入檔案末尾而不覆蓋原有內容是常見需求。關鍵在於 FileWriter 的建構子中將 append 參數設為 true。搭配 BufferedWriter 可提升寫入效能,並透過 try-with-resources 或 finally 區塊確保資源正確釋放。
BufferedWriter out = null;
try {
// 第二個參數 true 表示開啟附加模式
out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
} catch (IOException e) {
// 錯誤處理邏輯
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
true 時,資料會寫入檔案末尾;若為 false 或省略則會覆蓋檔案。finally 區塊關閉串流,避免檔案鎖定或資源洩漏。Java 7 以上建議使用 try-with-resources 自動管理。try (BufferedWriter writer = new BufferedWriter(new FileWriter("filename", true))) {
writer.write("aString");
writer.newLine(); // 可選:換行
} catch (IOException e) {
e.printStackTrace();
}
此寫法更簡潔,編譯器會自動生成關閉資源的程式碼,是當前推薦的最佳實踐。