BufferedInputStream的作用比较

参考:https://bbs.csdn.net/topics/390517474/

package com.zg.kyrie;


import java.io.*;

/**
 * @Auther: kyrie
 * @Date: 2018/8/23 21:50
 */
public class BufferedTest{
    private static final String movie = "D:\\迅雷下载\\[91xinpian.com]西虹市首富HDTC1080P清晰国语中字.mp4";   // 2.54G
    public static void main(String[] args) {
        long startTime1 = System.currentTimeMillis();
        readByBuffer(movie);
        long endTime1 = System.currentTimeMillis();
        System.out.println(endTime1 - startTime1);

        long startTime2 = System.currentTimeMillis();
        readByInput(movie);
        long endTime2 = System.currentTimeMillis();
        System.out.println(endTime2 - startTime2);
    }


    private static void readByBuffer(String movie) {
        BufferedInputStream bufferedInputStream = null;
        try{
            bufferedInputStream = new BufferedInputStream(new FileInputStream(movie));
            byte[] bytes = new byte[8192];
            while (bufferedInputStream.read(bytes) != -1){
            }

        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (bufferedInputStream != null){
                try{
                    bufferedInputStream.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    private static void readByInput(String movie) {
        InputStream inputStream = null;
        try{
            inputStream = new FileInputStream(movie);
            byte[] bytes = new byte[8192];
            while (inputStream.read(bytes) != -1){
            }

        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (inputStream != null){
                try{
                    inputStream.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

}

第一次:bytes为8192

2000
1906

用了bufferedInputstream的比直接用inputstream耗时还要多点,可以用回帖解释:

你这里,通过BufferedInputStream读取用的时间比通过InputStream读取用时时间长,是消耗在你从缓冲区里读取数据的时间。用了BufferedInputStream后你每次读取都是从缓冲区里拷贝数据,在后你再读,缓冲区没东西了就调IO从数据源读到缓冲区,然后你再从缓冲区读。为什么会这样呢,因为你自己建立的数组大小和缓冲区大小一样,根本就没起到缓冲作用。
当你程序的数组小于缓冲区的大小的时候才会起到缓冲作用。比如是byte[] b=new byte[2048];,你要读的数据是1G,那么你要调512次IO,假设一次1s,就512s,但如果用BufferedInputStream,你每从缓冲区读取4(8192/2048=4)次才调用一次IO(假设访问内存一次0.1s),总共要128次,就128s,加上总的从缓冲区拷贝数据的时间(512*0.1=51.2s),128+51.2=179.2。
这里用0.1s和1s来体现IO很耗时

第二次 bytes = 1024

2128
9129

明显用了缓冲区的快乐很多。

第三次 bytes = 512

2288
17411

测试可以看出,你设定的一次读取的字节数越少,BufferedInputStream发挥的作用越明显。因为它都是用默认的8192大小从磁盘或者网络获取/写入数据的,再从缓冲区读取到bytes,直到缓冲区被读取完毕才再通过IO读取剩余数据。这样就减少了很多耗时的IO读写操作,提高了读写效率。

同时可以看出,内存间的读取非常快,对总时长的影响很小,主要耗时在IO上,用了BufferedInputStream平均耗时都很少而且非常稳定,所以好处很明显啦。

猜你喜欢

转载自blog.csdn.net/liuchaoxuan/article/details/81989120