讀取包含中文的文字檔案時出現亂碼,是 Java 開發常見問題。核心原因在於編碼不一致:專案編碼、檔案實際編碼、JVM 預設編碼三者必須統一。本文提供完整解決方案與最佳實務代碼。
關鍵在於使用 InputStreamReader 明確指定 UTF-8 解碼,而非依賴系統預設編碼:
InputStreamReader isr = null;
BufferedReader reader = null;
List<String> lines = new ArrayList<>();
try {
// 關鍵:明確指定 UTF-8 解碼
isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
String trimmed = line.trim();
if (trimmed.length() > 1) { // 過濾空白行
lines.add(trimmed);
}
}
System.out.println("讀取完成,共 " + lines.size() + " 行有效資料");
} catch (UnsupportedEncodingException e) {
System.err.println("不支援的編碼格式: " + e.getMessage());
} catch (FileNotFoundException e) {
System.err.println("找不到檔案: " + filePath);
} catch (IOException e) {
System.err.println("讀取錯誤: " + e.getMessage());
} finally {
// 資源釋放 (Java 7+ 建議使用 try-with-resources)
try { if (reader != null) reader.close(); } catch (IOException ignored) {}
try { if (isr != null) isr.close(); } catch (IOException ignored) {}
}
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
String trimmed = line.trim();
if (trimmed.length() > 1) lines.add(trimmed);
}
} catch (IOException e) {
e.printStackTrace();
}
// 自動關閉資源,無需 finally 區塊
\uFEFF,需手動移除或使用 StandardCharsets.UTF_8 處理juniversalchardet 或 Apache Tika 自動偵測chcp 65001 或設定 IDE 控制台編碼遵循「編碼統一 + 明確指定解碼器」原則,即可徹底解決 Java 讀取中文檔案亂碼問題。