檔案 I/O 是 Java 開發中最基礎也最常用的功能之一。針對不同場景(二進位/文字、大檔案/小檔案、順序/隨機存取),Java 提供了多種 API。本文系統整理五種核心讀取方式,附完整可執行範例,幫助開發者根據需求選擇最適合的方案。
適用於二進位檔案(圖片、聲音、影片)或不需字元解碼的場景。
try (FileInputStream in = new FileInputStream(file)) {
int b;
while ((b = in.read()) != -1) {
System.out.write(b); // 輸出到標準輸出
}
}
try (FileInputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
System.out.write(buffer, 0, len);
}
}
適用於文字檔案,自動處理字元編碼轉換。
try (Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
int c;
while ((c = reader.read()) != -1) {
if (c != '\r') System.out.print((char) c); // 過濾 Windows 換行符 \r
}
}
try (Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
char[] buffer = new char[1024];
int len;
while ((len = reader.read(buffer)) != -1) {
System.out.print(buffer, 0, len);
}
}
最常用於處理設定檔、日誌、CSV 等逐行文本資料。
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
int lineNum = 1;
while ((line = br.readLine()) != null) {
System.out.println("Line " + lineNum++ + ": " + line);
}
}
支援跳轉至任意位置讀寫,適合大檔案分片處理或資料庫索引實作。
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
long fileLen = raf.length();
long start = fileLen > 4 ? 4 : 0; // 從第 4 位元組開始
raf.seek(start);
byte[] buffer = new byte[10];
int len;
while ((len = raf.read(buffer)) != -1) {
System.out.write(buffer, 0, len);
}
}
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
raf.seek(raf.length()); // 移至檔案末尾
raf.writeBytes(content);
}
try (FileWriter fw = new FileWriter(file, true)) { // true 表示追加模式
fw.write(content);
}
| 場景 | 推薦類別 | 關鍵優勢 |
|---|---|---|
| 二進位檔案、大檔案 | FileInputStream + 緩衝陣列 | 低記憶體佔用、高吞吐量 |
| 文字檔案、需編碼轉換 | InputStreamReader + 緩衝陣列 | 正確處理多國語言編碼 |
| 逐行處理邏輯 | BufferedReader | API 簡潔、自動處理換行符 |
| 需隨機跳轉讀寫 | RandomAccessFile | 支援 seek、read/write 任意位置 |
| 簡單追加寫入 | FileWriter(true) | 程式碼最精簡 |
public class FileReadDemo {
public static void main(String[] args) {
String path = "C:/temp/demo.txt";
readByBytes(path);
readByChars(path);
readByLines(path);
readByRandomAccess(path);
appendContent(path, "\nAppended line.");
readByLines(path); // 驗證追加結果
}
// ... 上述五個 static 方法實作
}
try-with-resources(JDK 7+)自動關閉資源,避免洩漏。StandardCharsets.UTF_8),避免跨平台亂碼。EOFException。掌握這五種讀取方式,即可應對 90% 以上的檔案處理需求。實務上建議封裝成通用工具類(如 FileUtils.readLines()),統一異常處理與編碼設定,提升團隊開發效率。