java 复制文件的 3 种方式

本文对比了使用FileInputStream/FileOutputStream、nio.FileChannel及Java1.7 Files类进行文件复制的三种方法,通过实测数据展示了不同复制方式的效率差异。

一、使用 FileInputStream,FileOutputStream 复制

使用 FileInputStream 读取文件 A 的字节,使用 FileOutputStream 写入到文件 B。代码:

  private static void copyFileUsingFileStreams(File source, File dest) throws IOException {    
      InputStream input = null;    
      OutputStream output = null;    
      
      try {
             input = new FileInputStream(source);
             output = new FileOutputStream(dest);        
             byte[] buf = new byte[1024];        
             int bytesRead;        
            while ((bytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, bytesRead);
            }
     } finally {
         input.close();
         output.close();
     }
 }


二、使用 nio.FileChannel 复制

Java NIO 包括 transferFrom 方法, 根据文档说明,应该比文件流复制的速度更快。代码:

  private static void copyFileUsingFileChannels(File source, File dest) throws IOException {    
          FileChannel inputChannel = null;    
          FileChannel outputChannel = null;    
      try {
          inputChannel = new FileInputStream(source).getChannel();
          outputChannel = new FileOutputStream(dest).getChannel();
          outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
      } finally {
          inputChannel.close();
         outputChannel.close();
     }
 }

三、使用 Java1.7 的 Files 类复制

使用 Java1.7 的Files 类的复制方法, 从一个文件复制到另一个文件。代码:

 private static void copyFileUsingJava7Files( File source, File dest ) throws IOException {    
         Files.copy(source.toPath(), dest.toPath());
 }

 

测试三种方法耗费的时间:
Time taken by FileInputStream/FileOutputStream Copy = 127572360
Time taken by FileChannels Copy = 10449963
Time taken by Java7 Files Copy = 10808333

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值