在看别人视屏和一些论坛时,发现很多人对于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调用的,是同一个类的同一个方法,再回头看部分人的解释,我们才发现,其实很多人也只是自以为自己知道而已,对于真相,其实还是需要实实在在的东西去证实,而不是给一个很宽泛的解释。