简介
缓冲流属于处理流的一种
缓冲流有四种:BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter
缓冲流可以提高文件读写的速度
BufferedInputStream和BufferedOutputStream
先使用非缓冲流测试复制1个G的文件
File src = new File("C:\Users\wj\Desktop\01.ts");
File dest = new File("C:\Users\wj\Desktop\01.1.ts");
long start = System.currentTimeMillis();
try(FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest)){
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
}catch (IOException e){
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-start);
耗费11s
BufferedInputStream和BufferedOutputStream的使用与FileInputStream和FileOutputStream差不多,这里不详细介绍。
这里jdk底层使用的装饰器设计模式,我们用BufferedInputStream包装FileInputStream即可,BufferedOutputStream也是如此。
File src = new File("C:\Users\wj\Desktop\01.ts");
File dest = new File("C:\Users\wj\Desktop\01.2.ts");
long start = System.currentTimeMillis();
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest))){
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1){
bos.write(buffer, 0, len);
}
}catch (IOException e){
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-start);
两秒多就可以完成:效率提升十分明显
内部原理:内部提供了一个缓存区
BufferedReader、BufferedWriter
测试按行读取并复制文本文件:
File src = new File("斗破苍穹.txt");
File dest = new File("斗破苍穹-buffered.txt");
long start = System.currentTimeMillis();
try(BufferedReader br = new BufferedReader(new FileReader(src));
BufferedWriter bw = new BufferedWriter(new FileWriter(dest))){
String line ;
//按行读取
while ((line = br.readLine()) != null){
bw.write(line);
bw.newLine();//换行
}
}catch (IOException e){
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(end-start);
复制出来的文件也是没有问题的