天天看點

java中講講BufferedInputStream的用法,舉例?

2.3 BufferedInputStream的用法

馬克-to-win:BufferedInputStream 顧名思義就是它有一個内部的buffer(緩存),它的read方法表面上看,雖然是隻讀了一個位元組,但它是開始時猛然從硬碟讀入一大堆位元組到自己的緩 存,當你read時,它是從緩存讀進一個位元組到記憶體。而前面講的FileInputStream位元組流,read時,都是真正每個位元組都從硬碟到記憶體,是 很慢的。為什麼?請研究硬碟的結構!下面的兩個例子,一個是FileInputStream的read生讀進來的,另一個是BufferedInputStream的隻能read,你比較一下讀的時間,差距蠻大的!

例:2.3.1

import java.io.*;

public class TestMark_to_win {

    public static void main(String args[]) throws FileNotFoundException,

            IOException {

        FileInputStream fis = new FileInputStream("c:/2.txt");

        long t = System.currentTimeMillis();

        int c;

        while ((c = fis.read()) != -1) {}

        fis.close();

        t = System.currentTimeMillis() - t;

        System.out.println("周遊檔案用了如下時間:" + t);

    }

}

例:2.3.2

        FileInputStream fis = new FileInputStream("i:\\2.txt");

        BufferedInputStream bis = new BufferedInputStream(fis);

        /*even though the next read() also read one byte, but because

BufferedInputStream has an internal buffer,when first time to read,

it will read in a whole buffer of byte from hard disk, then digest

these bytes one by one in memory */

        while ((c = bis.read()) != -1) {}