缓冲字节流
工作原理
可以看到,当时使用了缓冲字节流,复制文件的过程中,程序可以到达最少2此访问文件,因此大大提高了效率
实例
import java.io.*;
public class Tese03 {
public static void main(String[] args) throws IOException {
File file1 = new File("D:\\test\\a\\test01.txt"); //源文件
File file2 = new File("D:\\test\\a\\test02.txt"); //目标文件
FileInputStream fileInputStream = new FileInputStream(file1); //直接接触的字节流,直接跟源文件、目标文件接触
FileOutputStream fileOutputStream = new FileOutputStream(file2);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); //字节流外面包着的缓冲字节流
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte[] bytes =new byte[4]; //缓冲数组
int len = bufferedInputStream.read(bytes);
while (len != -1){
bufferedOutputStream.write(bytes,0,len);
len = bufferedInputStream.read(bytes);
}
bufferedOutputStream.close();
bufferedInputStream.close();
fileOutputStream.close();
fileInputStream.close();
}
}
当我们源文件内容较多时,我们可以明显看缓冲字节流和字节流复制文件效率差距
源文件
字节流消耗时间
缓冲字节流消耗时间
可以看到对于一个3KB大小源文件,普通字节流需要5毫秒时间复制,二缓冲字节流只需要1毫秒,可以明显看到这两种IO流效率差距