File:文件/目錄路徑抽象。FileInputStream:字節輸入流,讀取文件數據。FileOutputStream:字節輸出流,寫入文件數據。IOException:IO 操作異常基類。import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyDemo {
public static void main(String[] args) {
// 源文件與目標文件路徑
File srcFile = new File("d:/毫無保留.jpg");
File destFile = new File("d:/毫無保留Output.jpg");
// 緩衝區大小 16KB,平衡內存與系統調用次數
byte[] buffer = new byte[16 * 1024];
try (FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile)) {
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead); // 關鍵:只寫入實際讀取的字節數
}
System.out.println("文件複製成功:" + destFile.getAbsolutePath());
} catch (IOException e) {
System.err.println("文件操作失敗:" + e.getMessage());
e.printStackTrace();
}
}
}
byte[],循環讀寫,避免頻繁創建對象。fos.write(buffer, 0, bytesRead),最後一次讀取可能不滿緩衝區,必須用實際讀取長度。IOException 統一處理,打印堆棧便於排查。| 場景 | 優化方案 |
|---|---|
| 大文件(GB 級) | FileChannel.transferTo/transferFrom 零拷貝,OS 級優化 |
| 高併發複製 | 線程池 + 分片並行,或使用 Files.copy(Path, Path, StandardCopyOption.REPLACE_EXISTING) (NIO.2) |
| 進度顯示 | 在循環中累加 bytesRead,定時回調進度監聽器 |
| 校驗完整性 | 複製同時計算 MD5/CRC32,完成後比對 |
import java.nio.file.*;
import java.io.IOException;
public class NioCopyDemo {
public static void main(String[] args) {
Path src = Paths.get("d:/source.jpg");
Path dest = Paths.get("d:/target.jpg");
try {
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
System.out.println("NIO.2 複製完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
掌握 FileInputStream/OutputStream 循環讀寫模式是 Java IO 基礎。生產環境推薦 try-with-resources + 緩衝區複用,大文件優先考慮 FileChannel 零拷貝或 NIO.2 Files.copy。理解底層原理,才能根據場景選擇最高效方案。