FileInputStream,顾名思义,从文件流中读取数据。逐个字节读取,调用read()方法,每次由"字节输入流"对象从磁盘文件中读入一个字节到内存,此方法返回的是读取到的字节的内容,它是一个int类型0-255之间的字节值,读取至文件末尾返回-1。批量读取自建缓冲区,定义byte[]字节数组代表一个缓冲区。
//逐个字节读取方法1
InputStream in = null;
try {
//创建”字节流输入流”对象
in = new FileInputStream("E:\\test.txt");
//保存每次读取到字节值
int data = -1;
while((data = in.read())!= -1) {
System.out.print((char)data);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
in = null;
}
}
//逐个字节读取方法2
//创建”字节流输入流”对象
try (InputStream in = new FileInputStream("E:\\test.txt")) {
//保存每次读取到字节值
int data = -1;
while((data = in.read())!= -1) {
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
}
//批量读取
try (InputStream in = new FileInputStream("E:\\yuanjiuyuan\\girl.jpg")) {
byte[] buff = new byte[128];
int len = -1;
while((len = in.read(buff))!= -1) {
System.out.printf("本次读取的%d个字节:%s",len,Arrays.toString(buff));
}
} catch (IOException e) {
e.printStackTrace();
}
BufferedInputStream是缓冲输入流,自带缓冲区(默认大小8192个字节),必须配合FileInputStream类进行使用。作用是为另一个输入流添加一些功能,例如,提供缓冲功能。本质是通过一个内部缓冲区数组来实现的,每当缓冲区中的数据读完之后,输入流会再次填充数据缓冲区;如此反复,直到读完输入流的位置。
//带有缓冲区的字节输入流
//缓冲区默认大小8192
//逐个字节读取
try (BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("E:\\test.txt"))) {
//从内存的buff缓冲区中读取1个字节
int data = -1;
while((data = bis.read()) != -1) {
System.out.println(data);
}
} catch (IOException e) {
e.printStackTrace();
}
//批量字节读取
try (BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("E:\\test.txt"))) {
//从内存的buff缓冲区中读取1个字节
byte[] buff = new byte[128];
int data = -1;
while((data = bis.read(buff)) != -1) {
System.out.println(Arrays.toString(buff));
}
} catch (IOException e) {
e.printStackTrace();
}
逐个字节读取,每调用一次read()方法,都会去BufferedInputStream的缓冲区中读取一个字符,缓冲区内容读取完毕后,会一次性fill填充;批量字节读取,每调用一次read(buffData)方法,都会从BufferedInputStream的缓冲区中读取N个字节(N=buffData.length)
我们知道,从内存中读取数据的速度要比从硬盘读取数据的速度至少快10倍以上。以上就是两者的区别,如有不当之处还请大家多多指正,一起学习,一起进步!