java中利用串流装饰器进行文件读写的速度对比

本文采用四种方法将同样的数据从一个文件复制到另外一个文件中,并对其进行计时统计,并作了结果对比


四种方法分别为:

1,用基本字节流一次读写一个字节

2,用基本字节流一次读写一个字节数组

3,用高效字节流一次读写一个字节

4, 用高效字节流一次读写一个字节数组


下面来看代码:


package a003;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestDemo {

	public static void main(String[] args) throws IOException{
		long start=System.currentTimeMillis();
		Method1("h:\\a.txt","h:\\ed.txt");
		long end=System.currentTimeMillis();
		System.out.println("总耗时:"+(end-start)+"毫秒");
		
	}

//用高效字节流一次读写一个字节数组
	public static void Method4(String src,String dest)throws IOException{
			BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
			BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));
			byte[] bys=new byte[1024];

			int len=0;
			while((len=bis.read(bys))!=-1){
				bos.write(bys,0,len);
			}
				bis.close();
				bos.close();
	}
//用高效字节流一次读写一个字节
	public static void Method3(String src,String dest)throws IOException{
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));

		int len=0;
		while((len=bis.read())!=-1){
			bos.write(len);
		}
			bis.close();
			bos.close();
	}
//用基本字节流一次读写一个字节
	public static void Method1(String src,String dest)throws IOException{
		FileInputStream fis=new FileInputStream(src);
		FileOutputStream fos=new FileOutputStream(dest);

		int len=0;
		while((len=fis.read())!=-1){
			fos.write(len);
		}
			fis.close();
			fos.close();
	}
//用基本字节流一次读写一个字节数组
		public static void Method2(String src,String dest)throws IOException{
			FileInputStream fis=new FileInputStream(src);
			FileOutputStream fos=new FileOutputStream(dest);
			
			byte[] bys=new byte[1024];
			int len=0;
			while((len=fis.read(bys))!=-1){
				fos.write(bys,0,len);
			}
				fis.close();
				fos.close();
		}
}


计算结果统计对比:

method1:总耗时:127毫秒

method2:总耗时:1毫秒

method3:总耗时:32毫秒

method4:总耗时:1毫秒


从上面的输出结果可以看出,在同等情况下,一次传输一个字节数组的方法的传输速度明显高于一次传输一个字节的方法,不管是高效字节流还是普通的字节流中,尽管在method2和method4都为一毫秒,看起来似乎两个传输速度几乎相同。

但是,问题是因为文中测试的数据量太小,如果是数据量足够大的话,高效字节流的优势肯定会体现出来,读者不妨自己找一个大一点的数据试试,比如视频文件。


文中难免有不足之处,还望大家不吝纠正和指导,谢谢

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值