分別使用 FileReader/FileWriter(字元流)與 FileInputStream/FileOutputStream(位元組流)實現檔案複製,並比較適用場景。
package com.test.io;
import java.io.*;
public class JavaIODemo {
/** 字元流複製(適用文字檔) */
public boolean copyByChar(File srcFile, File destFile) {
try (FileReader fr = new FileReader(srcFile);
FileWriter fw = new FileWriter(destFile)) {
char[] buff = new char[1024];
int len;
while ((len = fr.read(buff)) != -1) {
fw.write(buff, 0, len);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/** 位元組流複製(適用二進位檔:圖片、影片、壓縮檔) */
public boolean copyByByte(File srcFile, File destFile, int bufferSize) {
try (FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile)) {
byte[] buff = new byte[bufferSize];
int len;
while ((len = fis.read(buff)) != -1) {
fos.write(buff, 0, len);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
JavaIODemo demo = new JavaIODemo();
File src = new File("src/com/test/io/JavaIODemo.java");
File destChar = new File("D:/JavaIODemo_Char.txt");
File destByte = new File("D:/JavaIODemo_Byte.txt");
System.out.println("字元流複製:" + (demo.copyByChar(src, destChar) ? "成功" : "失敗"));
System.out.println("位元組流複製:" + (demo.copyByByte(src, destByte, 1024) ? "成功" : "失敗"));
}
}
| 特性 | 字元流 (Reader/Writer) | 位元組流 (InputStream/OutputStream) |
|---|---|---|
| 處理單位 | char (2 bytes, UTF-16) | byte (1 byte) |
| 編碼轉換 | 自動依平台預設編碼 | 無,原始位元組 |
| 適用檔案 | 純文字、XML、JSON、CSV | 圖片、音訊、視訊、Class、Zip |
| 效能 | 略低(編碼轉換開銷) | 高,直接記憶體搬移 |
BufferedReader/BufferedWriter 或 BufferedInputStream/BufferedOutputStream 減少系統呼叫次數。Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING) 一行搞定,內部採用零拷貝最佳化。FileChannel.transferTo/transferFrom 實現零拷貝。