FileInputStream与BufferedInputStream有哪些区别?

区别一:FileInputStream是InputStream的子类,而BufferedInputStream的子类,是InputStream的间接子类
    代码依据:
FileInputStream: 
public class FileInputStream extends InputStream{}

BufferedInputStream :
public class BufferedInputStream extends FilterInputStream {}

区别二:他们两个在使用执行read()方法时,低层的实现各不相同:FileInputStream是直接从磁盘读取数据至内存;而
BufferedInputStream是直接从缓冲区获取数据,它的底层是维护了一块缓冲区域,它存在于内存中,其容量是8192个字节,
然后每次读取内容时,直接从这片缓冲区读取内容,这样它的效率较快;

代码依据:
FileInputStream:
public int read() throws IOException {
        return read0();
}
private native int read0() throws IOException;//本地方法,直接与操作系统交互

BufferedInputStream :
public synchronized int read() throws IOException {
        if (pos >= count) {
            fill();//一旦缓冲区的内容不足,就调用fill()方法,充满这片缓冲区
            if (pos >= count)
                return -1;
        }
        return getBufIfOpen()[pos++] & 0xff;
    }

private void fill() throws IOException {
        byte[] buffer = getBufIfOpen();
        if (markpos < 0)
            pos = 0;           
        else if (pos >= buffer.length)  
            if (markpos > 0) {  
                int sz = pos - markpos;
                System.arraycopy(buffer, markpos, buffer, 0, sz);
                pos = sz;
                markpos = 0;
            } else if (buffer.length >= marklimit) {
                markpos = -1;   
                pos = 0;        
            } else if (buffer.length >= MAX_BUFFER_SIZE) {
                throw new OutOfMemoryError("Required array size too large");
            } else {          
                int nsz = (pos <= MAX_BUFFER_SIZE - pos) ?
                        pos * 2 : MAX_BUFFER_SIZE;
                if (nsz > marklimit)
                    nsz = marklimit;
                byte nbuf[] = new byte[nsz];
                System.arraycopy(buffer, 0, nbuf, 0, pos);
                if (!bufUpdater.compareAndSet(this, buffer, nbuf)) {
                    throw new IOException("Stream closed");
                }
                buffer = nbuf;
            }
        count = pos;
        int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
        if (n > 0)
            count = n + pos;
    }

private byte[] getBufIfOpen() throws IOException {
        byte[] buffer = buf;
        if (buffer == null)
            throw new IOException("Stream closed");
        return buffer;
    }
private static int DEFAULT_BUFFER_SIZE = 8192;//缓冲区的默认容量是8192;
/*补充:
1.BufferedInputStream 使用了装饰器模式
2.它的底层仍旧自动调用了FileInputStream底层的rean0()方法,只不过它在读取数据之前底层就提前调用了,
它把数据读到缓冲区,这样内存读取数据时,就可以直接从缓冲区里读取,效率更快
*/

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值