1.mp3 (約 100MB)public class FileCopyBenchmark {
// 1. 單字節讀寫 (最慢)
public static void copyByte(File src, File dest) throws IOException {
try (FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest)) {
int b;
while ((b = in.read()) != -1) out.write(b);
}
}
// 2. 字節陣列讀寫 (10KB 緩衝)
public static void copyByteArray(File src, File dest) throws IOException {
try (FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest)) {
byte[] buf = new byte[10 * 1024];
int len;
while ((len = in.read(buf)) != -1) out.write(buf, 0, len);
}
}
// 3. 緩衝流單字節 (BufferedInputStream/OutputStream)
public static void copyBufferedByte(File src, File dest) throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest))) {
int b;
while ((b = in.read()) != -1) out.write(b);
}
}
// 4. 緩衝流 + 字節陣列 (推薦生產用)
public static void copyBufferedArray(File src, File dest) throws IOException {
try (FileInputStream in = new FileInputStream(src);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest))) {
byte[] buf = new byte[10 * 1024];
int len;
while ((len = in.read(buf)) != -1) out.write(buf, 0, len);
}
}
}
| 方式 | 耗時 (ms) | 相對性能 | 分析 |
|---|---|---|---|
| 單字節 | ~90,000 | 1x (基準) | 每字節一次系統調用,極大開銷 |
| 字節陣列 (10KB) | ~40 | 2250x | 減少系統調用,用戶態緩衝 |
| 緩衝流單字節 | ~550 | 160x | 內核緩衝有效,但單字節寫入仍頻繁調用 |
| 緩衝流 + 陣列 | ~30 | 3000x | 雙重緩衝 + 批量寫入,最快 |
read()/write(int)) 處理大文件。BufferedInputStream 更關鍵:聚合寫入減少磁碟 I/O。FileChannel.transferTo/transferFrom (零拷貝) 或 Files.copy() (JDK 7+),性能更優且代碼最簡潔:// 現代最佳實踐 (零拷貝,內核態直接傳輸)
Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
public static void copyNio(File src, File dest) throws IOException {
try (FileChannel in = FileChannel.open(src.toPath(), StandardOpenOption.READ);
FileChannel out = FileChannel.open(dest.toPath(), StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
in.transferTo(0, in.size(), out);
}
}
通常比 Buffered+Array 快 10%-30%,且 CPU 佔用極低。