码迷,mamicode.com
首页 > 编程语言 > 详细

关于Java缓冲流的一点误解

时间:2019-05-10 22:04:08      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:strong   buffere   机制   test   ring   读取   collect   定义   span   

我在网上看到很多输入流和输出流的代码是这样的:

public class BufferedTest {
    public static void main(String[] args) {
        InputStream in = null;
        OutputStream out = null;
        try  {
            // 此处为演示效果 将in和out都定义在try块内 防止自动关闭
            in = new BufferedInputStream(new FileInputStream("collect.txt"));
            int count = in.available();
            byte[] bytes = new byte[count]; // 通常大家都认为这是为缓冲流定义的缓冲字节数组
            if (count > 0)
                in.read(bytes);
            
            // 正常输出,好像也没什么问题,完美的缓冲机制
            for (byte b : bytes)
                System.out.print((char)b);
            System.out.println();
            
            // 再来看一下输出流
            out = new BufferedOutputStream(new FileOutputStream("test.txt"));
            out.write(bytes);  // 奇怪。。test.txt文件是空的
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

问题就出在byte[] bytes = new byte[count];这行代码定义的并不是缓冲区

在try块内加上一句out.flush(); 冲刷缓冲区,test.txt中的内容就正常了。

 

缓冲流的缓冲区是在构造器内配置的,默认值时8k

public BufferedInputStream(InputStream in, int size) {
        super(in);
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
        buf = new byte[size];
    }

read(byte[])write(byte[])方法是在InputStream和OutputStream中定义的

但是这两个流都是不带缓冲的

 

输入缓冲区与输出缓冲区的区别

输入:直接从文件读取缓冲区大小的字节,小于默认值时就有多少缓冲多少,程序直接从缓冲区读取字节

输出:只有将缓冲区写满,才输出一次,所以需要flush()方法或close()方法冲刷缓冲区

 

关于Java缓冲流的一点误解

标签:strong   buffere   机制   test   ring   读取   collect   定义   span   

原文地址:https://www.cnblogs.com/hello-mrz/p/10846905.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!