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

Java 讀取文字檔案中文亂碼完整解決方案:編碼統一與 InputStreamReader 實作

     編輯:Java 相關知識

Java 處理中文文字檔案編碼問題徹底指南

讀取包含中文的文字檔案時出現亂碼,是 Java 開發常見問題。核心原因在於編碼不一致:專案編碼、檔案實際編碼、JVM 預設編碼三者必須統一。本文提供完整解決方案與最佳實務代碼。

三大編碼一致性原則

  1. 專案編碼:IDE 專案設定為 UTF-8 (Eclipse: Properties → Resource → Text file encoding)
  2. 檔案編碼:文字檔實際儲存編碼為 UTF-8 (Notepad++/VS Code 另存新檔指定)
  3. 程式碼編碼:Java 原始碼檔案編碼為 UTF-8

正確讀取實作:指定 InputStreamReader 編碼

關鍵在於使用 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) {}
}

現代化寫法:Java 7+ try-with-resources

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 區塊

常見陷阱與除錯技巧

  • BOM 標記:UTF-8 with BOM 會導致第一行開頭出現 \uFEFF,需手動移除或使用 StandardCharsets.UTF_8 處理
  • 編碼偵測:不確定檔案編碼時,可用 juniversalchardet 或 Apache Tika 自動偵測
  • 控制台編碼:Windows CMD 預設 Big5/CP950,輸出中文需執行 chcp 65001 或設定 IDE 控制台編碼

遵循「編碼統一 + 明確指定解碼器」原則,即可徹底解決 Java 讀取中文檔案亂碼問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved