四种复制方法效率比较

    我们学过了IO流,复制文件是必不可少的,那我们采用哪种方式复制呢?哪种方式的效率更高呢?我们一起来比较一下吧,这样以后就可以根据需求采用合适的方法操作文件了。

【四种复制】

/*
 * 四种复制方法,比较速度
 */
public class Copy {
	public static void main(String[] args) throws IOException {
		File src=new File("f:\\博客书1.rar");//源路径
		File dest=new File("f:\\ab\\博客书1.rar");//目标路径
		copy_1(src,dest);//用字节一个一个复制
		copy_2(src,dest);//用字节数组复制
		copy_3(src,dest);//调用缓冲流一个字节一个字节进行复制
		copy_4(src,dest);//调用缓冲字节数组进行复制
	}
	//用字节一个一个复制
	public static void copy_1(File src,File dest) throws IOException{
		long s=System.currentTimeMillis();
		FileInputStream fis=new FileInputStream(src);
		FileOutputStream fos=new FileOutputStream(dest);
		int len=0;
		while((len=fis.read())!=-1){
			fos.write(len);
		}
		fos.close();
		fis.close();
		long e=System.currentTimeMillis();
		System.out.println("单个字节复制"+(e-s));
	}
	//用字节数组复制
	public static void copy_2(File src,File dest) throws IOException{
		long s=System.currentTimeMillis();
		FileInputStream fis=new FileInputStream(src);
		FileOutputStream fos=new FileOutputStream(dest);
		int len=0;
		byte [] b=new byte[1024];
		while((len=fis.read(b))!=-1){
			fos.write(b,0,len);
		}
		fos.close();
		fis.close();
		long e=System.currentTimeMillis();
		System.out.println("字节数组"+(e-s));
	}
	//调用缓冲一个字节一个字节进行复制
	public static void copy_3(File src,File dest) throws IOException{
		long s=System.currentTimeMillis();
		FileInputStream fis=new FileInputStream(src);
		BufferedInputStream bis=new BufferedInputStream(fis);
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));
		int len;
		while((len=bis.read())!=-1){
			bos.write(len);
		}
		bos.close();
		bis.close();
		fis.close();
		long e=System.currentTimeMillis();
		System.out.println("缓冲流单个字节复制"+(e-s));
	}
	//调用缓冲字节数组进行复制
	public static void copy_4(File src,File dest) throws IOException{
		long s=System.currentTimeMillis();
		FileInputStream fis=new FileInputStream(src);
		BufferedInputStream bis=new BufferedInputStream(fis);
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));
		int len;
		byte [] b=new byte[1024];
		while((len=bis.read(b))!=-1){
			bos.write(b,0,len);
		}
		bos.close();
		bis.close();
		fis.close();
		long e=System.currentTimeMillis();
		System.out.println("缓冲字节数组复制"+(e-s));
		
	}
}

【结果如下】

单位为毫秒


【总结】

    这个结果我们就能一目了然了,如果复制的文件比较小,采用哪种方式都是可以的,但是如果文件大了呢?就体现出缓冲流的作用了,以后具体文件具体分析,让我们的程序飞起来……

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值