BufferedInputStream研究

本文探讨了BufferedInputStream和FileInputStream中read(byte[])方法的实际调用方式。通过源码分析,揭示了BufferedInputStream如何继承自FilterInputStream,并最终调用了FileInputStream的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在看别人视屏和一些论坛时,发现很多人对于BufferedInputStream调用read(byte b[])方法,和FileInputStream的read(byte b[])方法比较时,都有如下的说辞:


或者


但其实我们看BufferedInputStream的源码,BufferedInputStream其实只有read(byte b[], int off, int len)和read()两个方法而已,那么我们调用的read(byte b[])到底是哪里来的呢?

很简单,跳转几次源码就能找到,过程如下:

1.其实read(byte b[])来自FilterInputStream,也就是BufferedInputStream的父类,我们知道BufferedInputStream使用的是装饰模式,我们构建BufferedInputStream的时候,往往会把FileInputStream实例传入,但我们用BufferedInputStream调用方法时,其实用的还是FileInputStream里面的read(byte b[])方法.

具体代码如下:

这里开始调用read(byte b[])方法

BufferedInputStream bis = new BufferedInputStream(
				new FileInputStream(srcFile));
		
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(destFile));
		int c ;
		
		byte[] buffer=new byte[8192];
		
		while((c = bis.read(buffer))!=-1){
			bos.write(buffer);
		}

然后进入父类

    public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }

    public int read(byte b[], int off, int len) throws IOException {
        return in.read(b, off, len);
    }
大家看到了,最后调用的父类里面的
in.read(b, off, len);
这个in参数,就是底层输入流
     * @param   in   the underlying input stream, or <code>null</code> if
     *          this instance is to be created without an underlying stream.
     */
    protected FilterInputStream(InputStream in) {
        this.in = in;
    }

也就是说这个in,就是我们传入的FileInputStream

是的,FileInputStream和BufferedInputStream调用的,是同一个类的同一个方法,再回头看部分人的解释,我们才发现,其实很多人也只是自以为自己知道而已,对于真相,其实还是需要实实在在的东西去证实,而不是给一个很宽泛的解释。



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值