FileWriter 內部使用系統預設編碼(中文 Windows 為 GBK/GB2312,英文為 ISO-8859-1),無法指定編碼,導致寫入 UTF-8 內容時產生亂碼或編碼不一致。
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 |
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 陣列,寫出時仍依系統編碼。