Java 中讀取文件內容有多種方式,各有適用場景。本文整理三種最經典的讀取方法,提供完整可運行代碼,並分析優缺點與適用場景,助你根據實際需求選擇最佳方案。
import java.io.*;
public class FileReadDemo {
public static void main(String[] args) {
String filePath = "D:\\1.xls"; // Windows 路徑需轉義反斜槓
try {
// ========== 方法一:BufferedReader 逐行讀取(推薦文本文件) ==========
System.out.println("=== 方法一:BufferedReader ===");
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
sb.append(line).append(System.lineSeparator());
}
// System.out.println(sb.toString()); // 如需完整字串
}
// ========== 方法二:FileInputStream 位元組一次性讀取(適合二進制/小文件) ==========
System.out.println("\n=== 方法二:FileInputStream ===");
try (FileInputStream is = new FileInputStream(filePath)) {
// 獲取文件長度創建位元組陣列(注意:大文件會 OOM!)
byte[] bytes = new byte[(int) new File(filePath).length()];
int read = is.read(bytes);
System.out.write(bytes, 0, read); // 直接輸出到控制台
System.out.println();
}
// ========== 方法三:FileReader 字符一次性讀取(適合小文本文件) ==========
System.out.println("\n=== 方法三:FileReader ===");
try (FileReader fr = new FileReader(filePath)) {
char[] chars = new char[(int) new File(filePath).length()];
int read = fr.read(chars);
String content = new String(chars, 0, read);
System.out.print(content);
}
} catch (FileNotFoundException e) {
System.err.println("文件未找到: " + filePath);
e.printStackTrace();
} catch (IOException e) {
System.err.println("讀取文件發生 I/O 錯誤");
e.printStackTrace();
}
}
}
| 維度 | 方法一:BufferedReader | 方法二:FileInputStream | 方法三:FileReader |
|---|---|---|---|
| 數據類型 | 字符流(文本) | 位元組流(二進制/文本) | 字符流(文本) |
| 讀取方式 | 逐行緩衝讀取 | 一次性讀入記憶體 | 一次性讀入記憶體 |
| 記憶體佔用 | 極低(行級緩衝) | 高(文件大小=陣列大小) | 高(文件大小=陣列大小) |
| 大文件適用性 | ✅ 極佳 | ❌ 易 OOM | ❌ 易 OOM |
| 編碼處理 | 依賴平台預設編碼 | 無編碼概念(原始位元組) | 依賴平台預設編碼 |
| 適用場景 | 日誌、CSV、大文本文件 | 圖片、視頻、小配置文件 | 小型文本文件、配置文件 |
JDK 7+ 強烈建議使用 java.nio.file.Files 簡化代碼並提升性能:
try (Stream<String> lines = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) {
lines.forEach(System.out::println);
}
List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
StandardCharsets.UTF_8),避免跨平台亂碼。