Java拷贝文件性能的测试

http://www.javabloger.com/article/java-copy-file-performance.html上看到Java拷贝文件的性能中介绍,使用NIO性能会很高,于是用NIO和org.apache.io.FileUtils的copyFile方法做了一下测试对比:

 

package com.demo.test.file;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

/**
 * @author user
 * Description: 操作文件
 * 2012-5-5
 */
public class HandleFile {
	
	/**
	 * Description: 采用java nio里面的FileChannel,非堵塞I/O的文件管道模式,是java 对稍大文件copy 运行效率最高的方式.
	 * @deprecated 如果只是Copy一个小文件或者运行的频率比较低,非NIO方式和NIO方式差不了多少。
	 * @param fileFromPath
	 * @param fileToPath
	 */
	public static void copyFile(String fileFromPath, String fileToPath)  {
        try {
            // 读取文件创建一个管道
            java.nio.channels.FileChannel srcChannel = new java.io.FileInputStream(fileFromPath).getChannel();
            
            // 在管道上创建一个输出的目标地址
            java.nio.channels.FileChannel dstChannel = new java.io.FileOutputStream(fileToPath).getChannel();
            
            // 进行文件复制
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            
            // 运行复制结束,并且关闭 输入/输出管道流
            srcChannel.close();
            dstChannel.close();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	public static void copyFile2(String srcPath, String destPath){
		try {
			FileUtils.copyFile(new File(srcPath), new File(destPath));
			
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public static void main(String[] args) {
		long initMils = System.currentTimeMillis();
		copyFile("D:\\亚健康学基础(scrom).zip", "D:\\tmp\\scorm.zip");
		long endMils = System.currentTimeMillis();
		System.out.println("NIO copyFile use time is:" + (endMils - initMils) + "MilliSeconds");
		
		long initMils2 = System.currentTimeMillis();
		copyFile("D:\\亚健康学基础(scrom).zip", "D:\\temp\\scorm.zip");
		long endMils2 = System.currentTimeMillis();
		System.out.println("org.apache.io.FileUtils copyFile use time is:" + (endMils2 - initMils2) + "MilliSeconds");
		
	}

}
 

运行结果如下:

 

NIO copyFile use time is:1282MilliSeconds
org.apache.io.FileUtils copyFile use time is:656MilliSeconds

 

 FileUtils的copyFile比使用NIO快差不多1倍,FileUtils的copyFile源码:

 

FileInputStream  input = new FileInputStream(srcFile);
FileOutputStream output = new FileOutputStream(destFile);

byte buffer[] = new byte[4096];
        long count = 0L;
        for(int n = 0; -1 != (n = input.read(buffer));)
        {
            output.write(buffer, 0, n);
            count += n;
        }

 可看出copyFile中的buffer数组的容量为4096,所以在操作大文件上更胜一筹。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值