← 返回首页
Java文件拷贝的四种方式之比较
发表时间:2022-07-21 23:18:37
Java文件拷贝的四种方式之比较

常见的Java文件复制有以下四种方式: - 传统的字节流实现 - NIO实现(推荐:速度最快) - Apache Commons IO的FileUtils - JDK自带的Files工具类

1.传统的带缓冲的字节流

public class TraditionFileCopyDemo {
    public static void copy(File src, File dest) {
        int len = -1; //每次读取的字节的个数
        byte[] buff = new byte[1024]; //一个kb的缓冲区。
        try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(dest));) {
            //一头读,一头写
            while ((len = bin.read(buff, 0, buff.length)) != -1) {
                bout.write(buff, 0, len);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

2.NIO的transferFrom方法

public class NioFileCopyDemo {
    public static void copy(File src, File dest) {
        try (FileChannel inputChannel = new FileInputStream(src).getChannel(); FileChannel outputChannel = new FileOutputStream(dest).getChannel();) {
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
   }
}

3.Apache Commons IO 的FileUtils

需要引入commons-io-2.11.0.jar

public class ApacheFileUtilFileCopyDemo {
    public static void copy(File src, File dest) {
        try {
            FileUtils.copyFile(src, dest);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

4.使用JDK自带的Files.copy

public class JavaFileUtilFileCopyDemo {
    public static void copy(File src, File dest) {
       try {
           //如果目标文件不存在则复制。
           if(!dest.exists()) {
               Files.copy(src.toPath(), dest.toPath());
           }
       }catch(Exception ex){
           ex.printStackTrace();
       }
    }
}

经过测试比较发现,以上四种文件复制方式的执行速度为: NIO Channel > Files.copy > 字节流 > Apache Commons IO