当前位置: 代码迷 >> J2SE >> BufferedInputStream有什么作用呢?感觉意思不大
  详细解决方案

BufferedInputStream有什么作用呢?感觉意思不大

热度:103   发布时间:2016-04-23 19:57:45.0
BufferedInputStream有什么作用呢?感觉意义不大啊
直接上代码:

public class InputStreamTest {
    private static final String FILENAME="E:\\电影\\[高清电影]阿甘正传.1994.美国.中文字幕.1280x720.rmvb";
    public static void main(String[] args) throws IOException {
        long l1 = readByBufferedInputStream();
        long l2 = readByInputStream();
        System.out.println("通过BufferedInputStream读取用时:"+l1+";通过InputStream读取用时:"+l2);
    }

    public static long readByInputStream() throws IOException {
        InputStream in=new FileInputStream(FILENAME);
        byte[] b=new byte[8192];
        int l=0;
        long start=System.currentTimeMillis();
        while(in.read(b,0,8192)!=-1){
        }
        long end=System.currentTimeMillis();
        return end-start;
    }

    public static long readByBufferedInputStream() throws IOException {
        BufferedInputStream in=new BufferedInputStream(new FileInputStream(FILENAME));
        byte[] b=new byte[8192];
        int l=0;
        long start=System.currentTimeMillis();
        while(in.read(b,0,8192)!=-1){
        }
        long end=System.currentTimeMillis();
        return end-start;
    }
}

以上代码,一共有两个方法,第一个就是用InputStream读取数据的,第二个就是用BufferedInputStream读取数据的,其他的代码都一样,至于缓冲数组大小为8192是因为BufferedInputStream里面的默认数组大小就是8192的。我那个文件大小是1.46G。

但是运行结果很令我诧异:
通过BufferedInputStream读取用时:705;通过InputStream读取用时:669
通过BufferedInputStream读取用时:727;通过InputStream读取用时:690
通过BufferedInputStream读取用时:721;通过InputStream读取用时:689


但是结果BufferedInputStream用时高于InputStream。虽然差的不多,但是在我映像中,BufferedInputStream应该明显小于InputStream的啊。
这个是为什么呢?BufferedInputStream的缓冲功能又是在什么时候用的呢?
个人所学浅薄,如有错误,不吝赐教!
------解决思路----------------------
另外,在用bufferedinputstream时,可以对buffersize参数调整一下,设成256K试试,效果肯定不一样.
当它的buffer设成256K时, fileinputstream设成8k时,前者还是要快一些的.
256 * 1024,  通过BufferedInputStream读取用时:2135;
通过InputStream (8K)读取用时:3353

两者都为256K时,通过BufferedInputStream读取用时:2220;通过InputStream读取用时:2319

我的机器,RAM:8G, x64 win7.
------解决思路----------------------
不带缓冲的操作,每读一个字节就要写入一个字节,由于涉及磁盘的IO操作相比内存的操作要慢很多,所以不带缓冲的流效率很低。带缓冲的流,可以一次读很多字节,但不向磁盘中写入,只是先放到内存里。等凑够了缓冲区大小的时候一次性写入磁盘,这种方式可以减少磁盘操作次数,速度就会提高很多!这就是两者的区别


------解决思路----------------------
3楼+1; BUFFERED缓冲区,是综合下来效率高,而不是读是速度比谁快。