API介绍:
解析:BufferedInputStream类是InputStream子类,内部管理一个字节数组,每次创建对象时,会调用底层读取若干个字节数组,调用read(),read(byte)方法对该管理数据进行读取,从而减少底层系统调用,提高读取效率。
构造方法:
public class Demo11 {
public static void main(String[] args) throws FileNotFoundException {
InputStream is = new FileInputStream("文件地址");
//设置默认缓冲区大小8192
BufferedInputStream in = new BufferedInputStream(is);
System.out.println(in);//输出对象地址
BufferedInputStream in2 = new BufferedInputStream(is,1024);
System.out.println(in2);//输出新的对象地址。
}
}
常用功能方法(与InputStream类功能一致):
public class Demo13 {
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("文件地址");
BufferedInputStream in = new BufferedInputStream(is);
int i= -1;
while((i=in.read())!=-1){
System.out.println((char)i);
}
byte [] bs = new byte[in.available()];
in.read(bs);
System.out.println(new String(bs));
in.close();
}
}
高效字节流文件复制操作:
复制文件:
public class Demo14 {
public static void main(String[] args) throws IOException {
BufferedInputStream out = new BufferedInputStream(new FileInputStream("文件地址"));
BufferedOutputStream in = new BufferedOutputStream(new FileOutputStream("文件地址"));
int i =-1;//一个一个读写
while((out.read())!=-1){
in.write(i);
}
//一堆一堆读写:
byte [] b=new byte[1024];
int len=-1;
while ((len=out.read(b))!=-1){
in.write(b,0,len);
}
out.close();
in.flush();
in.close();
System.out.println("复制成功!");
}
}
结论:使用高效率字节流进行读写操作,一个一个字节读写,与一堆一堆字节读写效率区别不大,原因是该对象中都有缓冲区。一堆一个字节写能节省的时间只是内存循环时间。开发中一个一个字节读写都可以是用。