在 Java 中使用 BufferedReader 逐行讀取包含中文的文字檔時,若編碼設定不一致,輸出往往會出現亂碼。核心原因在於:作業系統預設編碼、IDE 專案編碼、檔案實際儲存編碼、程式碼中指定的讀取編碼,這四者必須完全一致。
切勿使用預設編碼的 FileReader,改用 InputStreamReader 顯式指定:
InputStreamReader isr = new InputStreamReader(
new FileInputStream(fileUrl), "UTF-8");
import java.io.*;
import java.util.*;
public class ReadTxtUtf8 {
public static void main(String[] args) {
String fileUrl = "data.txt"; // 檔案路徑
List lines = new ArrayList<>();
try (InputStreamReader isr = new InputStreamReader(
new FileInputStream(fileUrl), "UTF-8");
BufferedReader 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() + " 行有效資料");
lines.forEach(System.out::println);
} catch (UnsupportedEncodingException e) {
System.err.println("不支援的編碼: " + e.getMessage());
} catch (FileNotFoundException e) {
System.err.println("找不到檔案: " + fileUrl);
} catch (IOException e) {
System.err.println("讀取錯誤: " + e.getMessage());
}
}
}
Files.readAllLines(Paths.get(fileUrl), StandardCharsets.UTF_8)。中文亂碼本質上是編碼不匹配。只要做到「專案、檔案、程式碼三方編碼一致」並「明確指定 UTF-8 讀取」,即可徹底解決。養成使用 InputStreamReader 顯式指定編碼的習慣,是避免亂碼的關鍵。