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

Java 檔案讀寫操作完全指南:從基礎到進階的最佳實踐

     編輯:Java 綜合教學

Java 檔案讀寫操作完全指南

在日常 Java 開發中,檔案讀寫是處理資料輸入輸出的核心技能。無論是讀取配置檔、處理日誌,還是處理二進位資料,掌握高效的 I/O 操作都至關重要。本文系統整理 Java 檔案讀寫的各種方式,並提供完整的程式碼範例供參考。

一、檔案讀取的四種核心方式

根據資料類型與讀取需求,Java 提供了四種主要的檔案讀取策略:

1. 位元組流讀取(適用於二進位檔案)

使用 FileInputStream 以位元組為單位讀取,適合圖片、音訊、視訊等二進位資料:

public static void readFileByBytes(String filename) {
    File file = new File(filename);
    try (FileInputStream in = new FileInputStream(file)) {
        // 單位元組讀取
        int temp;
        while ((temp = in.read()) != -1) {
            System.out.println(temp);
        }
        
        // 批次讀取(效率更高)
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            System.out.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2. 字元流讀取(適用於文字檔案)

透過 InputStreamReader 將位元組轉換為字元,支援指定編碼(如 UTF-8),避免中文亂碼:

public static void readFileByChars(String filename) {
    File file = new File(filename);
    try (Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
        char[] buffer = new char[1024];
        int charsRead;
        while ((charsRead = reader.read(buffer)) != -1) {
            System.out.print(new String(buffer, 0, charsRead));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3. 緩衝逐行讀取(效率最高,適用於行導向文字)

BufferedReader 提供 readLine() 方法,是處理大型文字檔的首選:

public static void readFileByLines(String filename) {
    File file = new File(filename);
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        String line;
        int lineNum = 1;
        while ((line = reader.readLine()) != null) {
            System.out.println("Line " + lineNum++ + ": " + line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

4. 隨機存取(RandomAccessFile)

支援任意位置跳轉讀寫,適合大檔案的斷點續傳或索引式存取:

public static void readFileRandomAccess(String filename) {
    try (RandomAccessFile raf = new RandomAccessFile(filename, "r")) {
        long fileLength = raf.length();
        long startPos = fileLength > 4 ? 4 : 0;
        raf.seek(startPos);
        
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = raf.read(buffer)) != -1) {
            System.out.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

二、檔案寫入的三種常見方法

根據效能需求與資料類型選擇適當的寫入方式:

1. FileOutputStream - 基礎位元組寫入

try (FileOutputStream fos = new FileOutputStream("output.dat")) {
    fos.write("Hello World".getBytes("UTF-8"));
}

2. FileWriter - 便利的字元寫入

try (FileWriter fw = new FileWriter("output.txt")) {
    fw.write("Hello World");
}

3. BufferedWriter - 高效能緩衝寫入(推薦大量資料)

try (BufferedWriter bw = new BufferedWriter(
        new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8"))) {
    for (int i = 0; i < 1000; i++) {
        bw.write("Line " + i);
        bw.newLine();  // 跨平台換行
    }
}

三、效能比較與最佳實踐建議

  • 大量資料讀寫:優先使用緩衝流(BufferedInputStream/BufferedOutputStream, BufferedReader/BufferedWriter)
  • 文字檔案:明確指定編碼(StandardCharsets.UTF_8),避免平台預設編碼差異
  • 資源管理:Java 7+ 請使用 try-with-resources 自動關閉流
  • 大檔案處理:考慮使用 NIO (FileChannel, MappedByteBuffer) 或記憶體映射檔案
  • 序列化物件:使用 ObjectOutputStream/ObjectInputStream

四、Java NIO.2 現代化檔案操作 (Java 7+)

java.nio.file.Files 提供了更簡潔的 API:

// 一次性讀取所有行
List lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);

// 串流式處理大檔案(惰性載入)
try (Stream stream = Files.lines(Paths.get("file.txt"))) {
    stream.filter(line -> line.contains("ERROR"))
          .forEach(System.out::println);
}

// 寫入檔案
Files.write(Paths.get("output.txt"), 
            Collections.singletonList("Content"), 
            StandardCharsets.UTF_8, StandardOpenOption.CREATE);

掌握這些檔案操作技巧,能顯著提升處理資料輸入輸出的效率與程式碼品質。建議根據實際業務場景選擇最適合的方式,並在程式碼中統一採用 try-with-resources 確保資源正確釋放。

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