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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值