在 Java 中讀取純文字檔是基礎且高頻的操作。本文將以「裝飾者模式」串聯 File、FileInputStream、InputStreamReader、BufferedReader 四大類別,說明各自職責與組合方式,並提供可直接執行的完整範例代碼。
| 類別 | 角色 | 關鍵方法 |
|---|---|---|
File | 文件句柄,代表路徑 | exists(), isFile() |
FileInputStream | 位元組輸入流,讀取原始 bytes | read() |
InputStreamReader | 橋樑:bytes → chars,指定編碼 | 建構子 (InputStream, charset) |
BufferedReader | 緩衝字符流,高效逐行讀取 | readLine() |
package com.campu;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class TxtFileReader {
/** 讀取 txt 文件並逐行列印
* @param filePath 絕對或相對路徑
*/
public static void readTxtFile(String filePath) {
// 建議明確指定編碼,避免中文亂碼
String encoding = "UTF-8";
File file = new File(filePath);
if (!file.isFile() || !file.exists()) {
System.out.println("找不到指定的文件:" + filePath);
return;
}
// try-with-resources 自動關閉資源 (Java 7+)
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println("讀取文件內容出錯");
e.printStackTrace();
}
}
public static void main(String[] args) {
// 請換成您實際的 txt 路徑
String path = "L:/Apache/htdocs/res/20121012.txt";
readTxtFile(path);
}
}
new InputStreamReader(stream, "UTF-8"),若不指定會用系統預設編碼,跨平台易亂碼。try-with-resources 確保流正確關閉,避免洩漏。BufferedReader 內建 8KB 緩衝,逐行讀取記憶體佔用極低,適合 GB 級大檔。Files.readAllLines(Path, Charset) 一次讀全檔;Java 8+ Files.lines() 回傳 Stream 惰性處理。\\ 或 /,建議統一用 / 跨平台相容。file -i 或編輯器確認編碼。file.exists() 判斷 → 拋 FileNotFoundException。掌握 File → FileInputStream → InputStreamReader → BufferedReader 的串聯邏輯,即能靈活處理各種文字檔讀取需求。記住「指定編碼、自動關閉、逐行處理」三原則,即可寫出健壯且高效的讀檔代碼。