FileInputStream继承InpuStream,BufferedInputStream继承FilterInputStream而FileterInputStream继承InputStream。也就是说它们俩都是InputStream的实现类。
InputStream是一个抽象类,里面定义了一个read()方法。
在其继承或间接继承的两这两个类中这两个方法是不一样的。FileInputStream.read()在读取文件的时候可以实现一个字节一个字节的去读,也可以一堆一堆的字节读。具体使用方法如下:
public static void main(String[] args) {
// TODO Auto-generated method stub
try (InputStream in = new FileInputStream("D:\\附件5\\CD1F3E2AAB9B6CD3980DA1DCD1AA07DD.pdf")){
byte[] buff = new byte[256];
int len = -1;
while((len = in.read(buff))!=-1) {
System.out.println(len+"个字节:"+Arrays.toString(buff));
}
}catch (IOException e) {
e.printStackTrace();
}
}
而BufferedInputStream具体来说是FilterInputStream的一个装饰器类。我们来看BufferedInputStream的几个源码。
public BufferedInputStream(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
private static int DEFAULT_BUFFER_SIZE = 8192;
public BufferedInputStream(InputStream in, int size) {
super(in);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
protected FilterInputStream(InputStream in) {
this.in = in;
}
这里说明了 BufferedInputStream是有一个byte[ ]来充当内部的一个缓冲区,实际上干活的还是FileInputStream。当你用BufferedInputStream.read()来读取一个文件的时候,会先把所读的字节先存入到缓冲区里面,再从缓冲区里面读。这样看好像两者没什么区别。但是在计算机操作的时候,缓冲区是在内存中的,而文件是在硬盘中的。读取内存中的数据会比读取硬盘中的数据快很多。
下面展示用BufferedInputStream.read()
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\\\附件5\\\\CD1F3E2AAB9B6CD3980DA1DCD1AA07DD.pdf"))) {
int date=-1;
while((date=bis.read())!=-1){
System.out.println(date);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}