关于带有Buffered的流加速的机制

为了体会Buffered的流在进行传输文件中的加速体现,特意做了下面的例子进行了验证,主要对比的是一个复制的操作,因为比较小的文件体现不出来的速度的快慢,所以,特意下载了一个mp3格式的文件来进行测试,具体的代码如下:

首先是不带buffered的流的传输:

//对比效率---->与上面形成对比
	@Test
	public void TestInput() {

		//指定源文件
		File oldFile = new File("Barbie - Good Time.mp3");
		//指定新文件
		File newFile = new File("Good Time.mp3");
		
		//指定读入写出流
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(oldFile);
			os = new FileOutputStream(newFile);
			
			//进行复制操作
			int len;
			byte b[] = new byte[1024];
			
			long start = System.currentTimeMillis();
			
			while((len = is.read(b)) != -1) {
				//写操作
				os.write(b, 0, len);
			}
			
			long end = System.currentTimeMillis();
			
			System.out.println("不加入缓冲流需要花费的时间为:" + (end - start));//130
			
		}catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//关流 
		if(os != null) {
			try {
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(is != null) {
			try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
	}

可以看到进行这个复制操作需要的时间为:159ms
在这里插入图片描述
而加入Buffered的流的代码如下:

@Test
	public void testBufferedInputStream() {
		
		//主要用来测试加入缓冲流的作用,加快传输的速度---->主要用来测试buffered的速度提升
		File file = new File("Barbie - Good Time.mp3");
		//文件格式为mp3需要用字节流来进行处理
		BufferedInputStream bis = null;
		//写操作
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(file));
			
			bos = new BufferedOutputStream(new FileOutputStream("Good Time.mp3"));
			
			int len;
			byte[] b = new byte[1024];
			
			long start = System.currentTimeMillis();
			
			while((len = bis.read(b)) != -1) {
				//写
				bos.write(b, 0, len);
			}
			
			long end = System.currentTimeMillis();
			
			System.out.println("加入缓冲流后需要花费的时间为:" + (end-start));//52
		}catch (IOException e) {
			e.printStackTrace();
		}
		
		//关流
		if(bos != null) {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(bis != null) {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

具体运行的时间如下:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值