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

解決 FileWriter 無法寫入 UTF-8 的最佳實踐:OutputStreamWriter 替代方案

     編輯:Java 相關知識

問題根因

FileWriter 內部使用系統預設編碼(中文 Windows 為 GBK/GB2312,英文為 ISO-8859-1),無法指定編碼,導致寫入 UTF-8 內容時產生亂碼或編碼不一致。

正確解法:OutputStreamWriter + FileOutputStream

public class Utf8FileWriter {
    public static void writeUtf8File(String path, String content) throws IOException {
        try (OutputStreamWriter out = new OutputStreamWriter(
                new FileOutputStream(path), StandardCharsets.UTF_8)) {
            out.write(content);
            out.flush();
        }
    }

    public static void main(String[] args) throws IOException {
        String xml = "這是測試。";
        writeUtf8File("cn/yethyeth/sample/resources/XML_UTF-8.xml", xml);
        System.out.println("success...");
    }
}

關鍵點解析

類別可指定編碼適用場景
FileWriter❌僅限系統預設編碼環境
OutputStreamWriter✅需指定編碼的文字寫入
Files.newBufferedWriter (NIO.2)✅Java 7+ 推薦,支援 Path、OpenOption

NIO.2 現代寫法 (Java 7+)

import java.nio.file.*;
import java.nio.charset.StandardCharsets;

public static void writeUtf8Nio(Path path, String content) throws IOException {
    Files.write(path, content.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}

常見誤區

  • 誤以為 FileWriter 建構子可傳編碼(實際無此建構子)。
  • 使用 new String(bytes, "UTF-8") 後再用 FileWriter 寫入,實則在 JVM 內部已轉為 char 陣列,寫出時仍依系統編碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved