| 構造方法 | 行為 |
FileWriter(String fileName) | 覆寫模式建立/截斷檔案 |
FileWriter(String fileName, boolean append) | append=true 為續寫模式 |
FileWriter(File file) | 接受 File 物件,覆寫模式 |
FileWriter(File file, boolean append) | File 物件 + 續寫控制 |
注意:JDK 11 前無法指定編碼,預設平台編碼 (Windows 多為 GBK/Big5,Linux 為 UTF-8),跨平台建議改用 Files.newBufferedWriter(path, StandardCharsets.UTF_8) (NIO.2)。
核心寫入方法
write(int c):寫單一字元
write(char[] cbuf) / write(char[] cbuf, int off, int len):寫字元陣列/片段
write(String str) / write(String str, int off, int len):寫字串/子字串
flush():強制刷新緩衝區到磁碟
close():關閉流,隱含 flush()
標準寫入範本 (Try-with-resources JDK 7+)
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterBestPractice {
public static void main(String[] args) {
String filePath = "C:/myDoc/intro.txt";
String content = "我熱愛我的團隊!\n第二行內容。";
// 1. 續寫模式 + BufferedWriter 提升效能
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true))) {
bw.write(content);
bw.newLine(); // 跨平台換行
bw.flush(); // 確保寫入磁碟
System.out.println("寫入成功");
} catch (IOException e) {
System.err.println("寫入失敗:" + e.getMessage());
e.printStackTrace();
}
}
}
進階:指定 UTF-8 編碼 (JDK 11+ 推薦寫法)
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.BufferedWriter;
import java.io.IOException;
public class ModernFileWriter {
public static void main(String[] args) {
Path path = Paths.get("C:/myDoc/utf8.txt");
String content = "UTF-8 編碼測試:中文、English、😀";
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write(content);
System.out.println("UTF-8 寫入完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
常見坑點與避雷指南
| 問題 | 原因 | 解決 |
| 中文亂碼 | 系統預設編碼非 UTF-8 | JDK 11+ 用 Files.newBufferedWriter(path, StandardCharsets.UTF_8);舊版用 OutputStreamWriter 指定編碼 |
| 大量寫入極慢 | 無緩衝,每次 write 觸發系統呼叫 | 務必包裝 BufferedWriter (預設 8KB 緩衝) |
| 檔案被鎖定無法刪除 | 流未正確關閉 | 使用 try-with-resources 自動關閉 |
| 續寫無效 | 構造方法未傳 append=true | new FileWriter(file, true) |
效能對比參考 (寫入 10MB 文字)
FileWriter 直寫:~1200 ms
BufferedWriter (8KB):~45 ms
Files.write(path, bytes, StandardOpenOption.APPEND) (NIO.2):~30 ms
總結
- 簡單工具類/測試:
FileWriter + BufferedWriter 足矣。
- 生產環境/跨平台:優先
Files.newBufferedWriter (NIO.2) 明確指定 UTF-8。
- 超大檔案/高併發:考慮
MappedByteBuffer 或非同步 NIO (AsynchronousFileChannel)。
- 永遠使用 try-with-resources 確保資源釋放。
- 上一篇文章: Java Random 類用法詳解:產生偽隨機數的核心 API 與實戰技巧
- 下一篇文章: Java File 類操作檔案與目錄屬性完全指南:建立、刪除、遍歷、屬性查詢實戰
Copyright ©
程式碼之家 All Rights Reserved