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

Java 位元組流檔案讀寫完整教學:BufferedInputStream/OutputStream 高效複製二進位檔案

     編輯:Java 相關知識

掌握 Java 位元組流檔案操作核心模式:FileInputStream/FileOutputStream 搭配 BufferedInputStream/BufferedOutputStream 實現高效二進位檔案(圖片、視頻、壓縮包等)複製。本文提供標準範本代碼,涵蓋參數檢查、資源管理、異常處理全流程。

核心代碼範本


import java.io.*;
public class CopyBytes {
    public static void main(String[] args) throws IOException {
        if (args.length < 2) {
            System.out.println("Usage: java CopyBytes source_file target_file");
            return;
        }
        String src = args[0], dest = args[1];
        File inputFile = new File(src);
        File outputFile = new File(dest);
        // try-with-resources 自動關閉資源 (JDK 7+)
        try (FileInputStream in = new FileInputStream(inputFile);
             BufferedInputStream bin = new BufferedInputStream(in);
             FileOutputStream out = new FileOutputStream(outputFile);
             BufferedOutputStream bout = new BufferedOutputStream(out)) {
            int b;
            while ((b = bin.read()) != -1) {
                bout.write(b);
            }
        } catch (IOException e) {
            System.err.println("File operation failed: " + e.getMessage());
        }
    }
}

關鍵類別職責

類別角色備註
FileInputStream位元組輸入流,連接檔案適用於二進位資料
BufferedInputStream緩衝位元組輸入,減少系統調用內部維護 8KB 預設緩衝區
FileOutputStream位元組輸出流,連接檔案預設覆蓋,追加用 new FileOutputStream(file, true)
BufferedOutputStream緩衝位元組輸出,批量寫入需手動 flush() 強制寫入磁碟

效能優化關鍵:批量讀寫

單位元組讀寫(read()/write(int))效能極差,生產環境必須使用陣列緩衝:


byte[] buffer = new byte[8192]; // 8KB 緩衝區
int len;
while ((len = bin.read(buffer)) != -1) {
    bout.write(buffer, 0, len);
}

此模式將系統調用次數降低數千倍,是大檔案複製的標準做法。

NIO.2 現代替代方案 (JDK 7+)


import java.nio.file.*;
Files.copy(Paths.get(src), Paths.get(dest), StandardCopyOption.REPLACE_EXISTING);
// 或零複製(需 OS 支援):
Files.copy(Paths.get(src), Paths.get(dest), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

Files.copy() 內部可能使用零複製,效能更優,代碼更簡潔,推薦為首選。

常見錯誤避坑

  1. ❌ 文字檔案用位元組流複製無錯誤,但跨平台換行符(CRLF/LF)不會自動轉換 —— 文字檔請用字元流。
  2. ❌ 忘記 bout.flush() 導致最後緩衝區資料未寫入磁碟 —— try-with-resources 會自動 close() 觸發 flush。
  3. ❌ 大檔案不使用緩衝區直接單位元組複製,速度極慢 —— 必須用 byte[] buffer 批量讀寫。

字元流 vs 位元組流 選型口訣

文字檔(.txt, .csv, .xml, .json, .java, .properties)→ 字元流
二進位檔(.jpg, .mp4, .zip, .pdf, .class, .exe)→ 位元組流
不確定時 → 位元組流通用,字元流專用
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved