缓冲流的基本知识

编程入门 行业动态 更新时间:2024-10-22 08:22:57

缓冲流的<a href=https://www.elefans.com/category/jswz/34/1768060.html style=基本知识"/>

缓冲流的基本知识

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

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把当前缓存区的内容写出到文件中,但是多次调用会增加实际写出的次数从而降低写的效率,所以也要根据实际情况来调用。

更多推荐

缓冲流的基本知识

本文发布于:2024-02-05 08:35:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1673834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:基本知识

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!