BufferedOutputStream和BufferedInputStream 字节缓冲流
字节缓冲流
- 创建字节缓冲流对象,参数传入文件输入输出流对象
- 真正的读写依旧是字节流(文件输入输出流)
- 缓冲流使读写过程提速
- 字节缓冲流在底层实际上也是创建了字节数组(该数组的长度为8192)
public BufferedOutputStream(OutputStream out) {
this(out, 8192);
}
public BufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
示例1 使用字节缓冲流提升读写效率(内存中两个字节缓冲流数组间单字节传输字节)
import java.io.*;
public class BufferedDemo1 {
public static void main(String[] args) throws IOException{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\BaiduNetdiskDownload\\AE自制特效片段\\星轨.mov"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io-practice\\星轨(通过字节缓冲流提速).mov"));
int b;
while((b = bis.read()) != -1){
bos.write(b);
}
bis.close();
bos.close();
}
}
- 在底层(数据源硬盘到内存再到目标硬盘)
- read()从数据源硬盘直接读取8192个字节,存储到内存中的字节缓冲输入流创建的字节数组中
- 再在内存中----将该字节数组中的元素一个一个地传入内存中的字节缓冲输出流创建的字节数组中
- 最后再通过write()方法将这个包含8192个字节元素的数组直接写入到目标硬盘中,
- 减少了硬盘和内存直接读写的次数,从而极大地节约了读写时间,因为内存的运行速度比硬盘要快很多!!
示例2 通过创建字节数组来提升使用缓冲字节流时的读写速度(内存中两个字节缓冲流数组通过字节数组传输字节)
import java.io.*;
public class BufferedDemo2 {
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\BaiduNetdiskDownload\\AE自制特效片段\\星轨.mov"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io-practice\\星轨(通过字节数组使缓冲字节流提速).mov"));
byte[] byteArray = new byte[1024];
int len;
while((len = bis.read(byteArray)) != -1){
bos.write(byteArray,0,len);
}
bis.close();
bos.close();
}
}
- 在底层上,和单字节传输的缓冲字节流不同之处在于
- 在内存中字节缓冲输入流的数组与字节缓冲输出流的数组进行字节交换时,使用的是长度为1024的字节的数组,而不是一个一个字节进行交换
- 提升了在内存进行字节交换的效率