掌握 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);
}
此模式將系統調用次數降低數千倍,是大檔案複製的標準做法。
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() 內部可能使用零複製,效能更優,代碼更簡潔,推薦為首選。
bout.flush() 導致最後緩衝區資料未寫入磁碟 —— try-with-resources 會自動 close() 觸發 flush。byte[] buffer 批量讀寫。文字檔(.txt, .csv, .xml, .json, .java, .properties)→ 字元流
二進位檔(.jpg, .mp4, .zip, .pdf, .class, .exe)→ 位元組流
不確定時 → 位元組流通用,字元流專用