缓冲流的基本知识

拥有加快读写速度的功能,文件输出流是一次只读一个字节,缓冲输出流其实底层是一次读取一组字节

BufferedOutputstream

		FileInputStream fis = new FileInputStream("集体照1.jpg");
		FileOutputStream fos = new FileOutputStream("集体照3.jpg");
		int d = -1;
		long start = System.currentTimeMillis();
		while((d=fis.read())!=-1){
			fos.write(d);
		}
		long end = System.currentTimeMillis();
		System.out.println("复制完毕,耗时"+(end-start)+"ms");
		fos.close();

在这里插入图片描述
在用BufferedOutputstream套在fos上面之后

		FileInputStream fis = new FileInputStream("集体照1.jpg");
		BufferedInputStream bis = new BufferedInputStream(fis);
		FileOutputStream fos = new FileOutputStream("集体照3.jpg");
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		
		int d = -1;
		long start = System.currentTimeMillis();
		while((d=bis.read())!=-1){
			bos.write(d);
		}
		long end = System.currentTimeMillis();
		System.out.println("复制完毕,耗时"+(end-start)+"ms");
		bos.close();

在这里插入图片描述
缓冲流的加速功能显而易见。
但是缓冲流也有个缺点,就是它每次读写都是块读写,这样就可能导致有时候需要读写的内容填不满它的“缓冲区”,但是我们又需要它把未填满的“缓冲区”写完,所以这时候就可以调用它的flush()方法。

FileOutputStream fos = new FileOutputStream("aaa.txt");
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		String str = "红尘多可笑,痴情最无聊";
		bos.write(str.getBytes("gbk"));
		
		bos.flush();
		//需要有即时性的效果就要调用此方法,但是多次调用会降低写的效率
		System.out.println("写出完毕");
		bos.close();

flush()方法是要求bos把当前缓存区的内容写出到文件中,但是多次调用会增加实际写出的次数从而降低写的效率,所以也要根据实际情况来调用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值