首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java FileWriter 寫入文字檔完整指南:緩衝、編碼與資源管理最佳實踐

     編輯:Java 程式設計入門

FileWriter 核心定位

java.io.FileWriter 是字元流寫入文字檔的便利類,內部封裝 FileOutputStream + OutputStreamWriter,預設使用系統預設字元編碼與緩衝區大小。適合簡單文字寫入,大量資料建議搭配 BufferedWriter。

關鍵構造方法

注意: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();
        }
    }
}

常見坑點與避雷指南

構造方法行為
FileWriter(String fileName)覆寫模式建立/截斷檔案
FileWriter(String fileName, boolean append)append=true 為續寫模式
FileWriter(File file)接受 File 物件,覆寫模式
FileWriter(File file, boolean append)File 物件 + 續寫控制
問題原因解決
中文亂碼系統預設編碼非 UTF-8JDK 11+ 用 Files.newBufferedWriter(path, StandardCharsets.UTF_8);舊版用 OutputStreamWriter 指定編碼
大量寫入極慢無緩衝,每次 write 觸發系統呼叫務必包裝 BufferedWriter (預設 8KB 緩衝)
檔案被鎖定無法刪除流未正確關閉使用 try-with-resources 自動關閉
續寫無效構造方法未傳 append=truenew 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 確保資源釋放。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved