带缓冲区的FileInputStream和BufferedInputStream之间的区别

时间:2018-12-12 03:28:15

标签: fileinputstream bufferedinputstream

我正在研究java I/O,我想知道一些东西。

两者之间有什么区别?

@Test
public void fileInputReadWithBuffer() throws IOException {
    FileInputStream fileInputStream = new FileInputStream("/Users/home/Desktop/test.mov");

    byte[] temp = new byte[8192];

    int n;
    long start = System.currentTimeMillis();
    while((n = fileInputStream.read(temp)) != -1){
    }
    long end = System.currentTimeMillis();

    System.out.println((end - start) / 1000.0);
}

@Test
public void bufferedInputRead() throws IOException {
    BufferedInputStream bufferedInputStream =
            new BufferedInputStream(new FileInputStream("/Users/home/Desktop/test.mov"));

    int n;
    long start = System.currentTimeMillis();
    while((n = bufferedInputStream.read()) != -1){
    }
    long end = System.currentTimeMillis();

    System.out.println((end - start) / 1000.0);
}  

我以为是相同的(因为BufferedInputStream使用内部字节缓冲区,默认值为8192),
但事实并非如此。

使用BufferedInputStream without external buffer的速度要慢得多。
第一次测试耗时0.144秒,第二次测试耗时6.55秒。
test.mov文件大小为202MB

那么..两者之间有什么区别?

而且,当我使用下面的代码时会发生什么?

@Test
public void bufferedInputReadWithBuffer() throws IOException {
    BufferedInputStream bufferedInputStream =
            new BufferedInputStream(new FileInputStream("/Users/home/Desktop/test.mov"));

    byte[] temp = new byte[8192];

    int n;
    long start = System.currentTimeMillis();
    while((n = bufferedInputStream.read(temp)) != -1){
    }
    long end = System.currentTimeMillis();

    System.out.println((end - start) / 1000.0);
}

尽管它也使用了外部缓冲区,但它似乎比FileInputStream with external buffer慢。
当我在上面使用时,内部缓冲区会发生什么?

0 个答案:

没有答案
相关问题