使用 BufferedReader 包裝 FileReader,逐行讀取並保留換行符,配合 try-with-resources 或 finally 確保資源釋放。
import java.io.*;
public class ReadTextFileExample {
public static void main(String[] args) {
File file = new File("test.txt");
StringBuilder contents = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
contents.append(line)
.append(System.lineSeparator());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(contents.toString());
}
}
| 要點 | 說明 |
|---|---|
| BufferedReader | 提供緩衝讀取,大幅提升 I/O 性能 |
| readLine() | 不包含換行符,需手動添加 System.lineSeparator() |
| StringBuilder | 非線程安全但高效,單線程場景優於 StringBuffer |
| try-with-resources | Java 7+ 自動關閉實現 AutoCloseable 的資源 |
| 異常處理 | 分別捕獲 FileNotFoundException 與 IOException |
List lines = Files.readAllLines(Paths.get("test.txt"), StandardCharsets.UTF_8);
String content = String.join(System.lineSeparator(), lines);
try (Stream stream = Files.lines(Paths.get("test.txt"))) {
stream.forEach(System.out::println);
}
// 顯式指定編碼,避免平台預設編碼差異
new FileReader(file) // 依賴平台預設編碼,不推薦
new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8) // 推薦
選擇適合場景的讀取方式,兼顧性能與代碼簡潔。