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

import java.io.*;
public class TestMark_to_win {
    public static void main(String args[]) throws FileNotFoundException,
            IOException {
        FileInputStream fis = new FileInputStream("i:\\2.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        long t = System.currentTimeMillis();
        int c;
        /*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) {}
        fis.close();
        t = System.currentTimeMillis() - t;
        System.out.println("遍歷文件用了如下時間:" + t);
    }
}

更多請見:https://blog.csdn.net/qq_44639795/article/details/102549001


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM