首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 讀取檔案完整指南:五種核心方法詳解

     編輯:Java 相關知識

前言

檔案 I/O 是 Java 開發中最基礎也最常用的功能之一。針對不同場景(二進位/文字、大檔案/小檔案、順序/隨機存取),Java 提供了多種 API。本文系統整理五種核心讀取方式,附完整可執行範例,幫助開發者根據需求選擇最適合的方案。

一、按位元組讀取(Byte Stream)

適用於二進位檔案(圖片、聲音、影片)或不需字元解碼的場景。

1. 單位元組讀取

try (FileInputStream in = new FileInputStream(file)) {
    int b;
    while ((b = in.read()) != -1) {
        System.out.write(b); // 輸出到標準輸出
    }
}

2. 緩衝位元組陣列讀取(推薦)

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);
    }
}

二、按字元讀取(Character Stream)

適用於文字檔案,自動處理字元編碼轉換。

1. 單字元讀取

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
    }
}

2. 緩衝字元陣列讀取

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);
    }
}

三、按行讀取(BufferedReader)

最常用於處理設定檔、日誌、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);
    }
}

四、隨機存取(RandomAccessFile)

支援跳轉至任意位置讀寫,適合大檔案分片處理或資料庫索引實作。

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);
    }
}

五、將內容追加至檔案尾端

方法 A:RandomAccessFile

try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
    raf.seek(raf.length()); // 移至檔案末尾
    raf.writeBytes(content);
}

方法 B:FileWriter(append 模式)

try (FileWriter fw = new FileWriter(file, true)) { // true 表示追加模式
    fw.write(content);
}

效能與選擇建議

場景推薦類別關鍵優勢
二進位檔案、大檔案FileInputStream + 緩衝陣列低記憶體佔用、高吞吐量
文字檔案、需編碼轉換InputStreamReader + 緩衝陣列正確處理多國語言編碼
逐行處理邏輯BufferedReaderAPI 簡潔、自動處理換行符
需隨機跳轉讀寫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()),統一異常處理與編碼設定,提升團隊開發效率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved