缓冲流
缓冲流,也叫高校流,按照数据类型分类:
- 字节缓冲流:
BufferedInputStream
,BufferedOutputStream
- 字符缓冲流:
BufferedReader
,BufferedWriter
缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。
构造方法
public BufferedInputStream(InputStream in)
:创建一个新的缓冲字节输入流。
public BufferedOutputStream(OutputStream out)
: 创建一个新的缓冲字节输出流。
构造举例,代码如下:
1 2 3 4
| BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));
|
public BufferedReader(Reader in)
:创建一个 新的缓冲字符输入流。
public BufferedWriter(Writer out)
: 创建一个新的缓冲字符输出流。
构造举例,代码如下:
1 2 3 4
| BufferedReader br = new BufferedReader(new FileReader("br.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
|
效率测试
我在当前项目中有一个文件名为jdk-8u212-linux-x64.tar.gz
的文件(文件大小185M),现在分别使用普通字节流和缓冲字节流进行复制测试,并分别记录消耗的时长。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.tipdm.demo1;
import java.io.*;
public class demo1 { public static void main(String[] args) throws IOException { long start,end; start = System.currentTimeMillis(); FileInputStream fileInputStream1 = new FileInputStream("day10-code\\jdk8.tar.gz"); FileOutputStream fileOutputStream1 = new FileOutputStream("day10-code\\copy1.tar.gz");
byte[] bytes = new byte[1024]; int len; while((len=fileInputStream1.read(bytes))!= -1){ fileOutputStream1.write(bytes, 0 ,len); } end = System.currentTimeMillis(); System.out.println("普通字节流消耗时长:" + (end - start)); fileOutputStream1.close(); fileInputStream1.close();
start = System.currentTimeMillis(); BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("day10-code\\jdk8.tar.gz")); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("day10-code\\copy2.tar.gz")); while((len=bufferedInputStream.read(bytes)) != -1){ bufferedOutputStream.write(bytes, 0, len); } end = System.currentTimeMillis(); System.out.println("缓冲字节流消耗时长:" + (end - start));
bufferedOutputStream.close(); bufferedInputStream.close(); } }
|
1 2 3 4
| 普通字节流消耗时长:553 缓冲字节流消耗时长:167
进程已结束,退出代码0
|
从结果可以看出,缓冲字节流的运行效率是普通字节流的3~4倍。
字符流与缓冲字符串的使用方式和优缺点与字节流一模一样,不再赘述。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package com.tipdm.demo1;
import java.io.*;
public class demo2 { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader("a.txt")); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("res.txt"));
bufferedReader.readLine(); bufferedWriter.write("可以直接写出字符串"); bufferedWriter.newLine(); } }
|