区别一: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()方法,只不过它在读取数据之前底层就提前调用了,
它把数据读到缓冲区,这样内存读取数据时,就可以直接从缓冲区里读取,效率更快
*/