文件操作是 Java 開發的基本功。本文將從傳統 IO 流實現入手,分析其缺陷,並引導你遷移至現代 NIO.2 API,掌握高效、健壯的文件複製與移動方案。
原始代碼使用 `FileInputStream`/`FileOutputStream` 配合緩衝流實現複製,邏輯清晰但存在隱患:
現代 Java 開發強烈推薦使用 `java.nio.file.Files`,原子性、鏈式調用、異常安全一應俱全。
import java.nio.file.*;
import java.io.IOException;
public void copyFileModern(Path source, Path target) throws IOException {
// 標準複製,支援覆蓋、保留屬性、跟隨符號鏈接
Files.copy(source, target,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES,
LinkOption.NOFOLLOW_LINKS);
}
public void moveFileModern(Path source, Path target) throws IOException {
// 同一文件系統下為原子性重命名;跨文件系統則複製+刪除
Files.move(source, target,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
}
若需處理 GB 級文件,可利用 `FileChannel.transferTo/From` 實現內核態零拷貝,或 `MappedByteBuffer` 內存映射,避免用戶態緩衝區開銷:
try (FileChannel in = FileChannel.open(source, StandardOpenOption.READ);
FileChannel out = FileChannel.open(target, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
long transferred = 0;
long size = in.size();
while (transferred < size) {
transferred += in.transferTo(transferred, size - transferred, out);
}
}
從手工搬運字節到聲明式文件操作,Java IO 的演進反映了軟體工程對可靠性與效率的持續追求。掌握 NIO.2 不僅能寫出更專業的代碼,更能在面對海量數據時游刃有餘。