什么是缓冲流
缓冲流就是为读写流的创建一个缓冲区,通过缓冲区进行读写。
分为四类:BufferedInputStream,BufferedOutputStream,BufferedReader, BufferedWriter
为什么需要缓冲流
使用非缓冲流时,每次读写操作系统都会进行I/O操作,I/O操作是很耗时的。
如果能为读写流的创建一个缓冲区,通过缓冲区进行读写,就能减少操作系统I/O的次数,从而提高读写六的速度。
如何使用缓冲流
BufferedInputStream,BufferedOutputStream
下面是一个复制文件的例子
需要注意的是必须使用一个InputStream/OutputStream来创建BufferedInputStream/BufferedOutputStream
public static void main(String[] args) {
try (InputStream in = new BufferedInputStream(new FileInputStream(new File("a.txt")));
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("a.txt.bak")))) {
byte[] buff = new byte[1024];
int len = -1;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
// out.flush(); close 方法中会调用flush
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader, BufferedWriter
下面是一个复制文件的例子
public static void main(String[] args) {
try (Reader reader = new BufferedReader(new FileReader(new File("a.txt")));
Writer writer = new BufferedWriter(new FileWriter(new File("a.txt.bak")))) {
char[] buff = new char[1024];
int len = -1;
while ((len = reader.read()) != -1) {
writer.write(buff, 0, len);
}
// writer.flush(); close 方法中会调用flush
} catch (IOException e) {
e.printStackTrace();
}
}
缓冲流与非缓冲流的速度对比
使用缓冲流复制文件用时
public static void main(String[] args) {
long start = System.currentTimeMillis();
try (InputStream in = new BufferedInputStream(new FileInputStream(new File("D:\\soft\\jdk-14.0.2_windows-x64_bin.zip")));
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("D:\\soft\\jdk-14.0.2_windows-x64_bin.zip.bak")))) {
byte[] buff = new byte[1024];
int len = -1;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
// out.flush(); close 方法中会调用flush
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("用时:" + (System.currentTimeMillis() - start));
}
运行结果
用时:280
使用非缓冲流复制文件用时
public static void main(String[] args) {
long start = System.currentTimeMillis();
try (InputStream in = new FileInputStream(new File("D:\\soft\\jdk-14.0.2_windows-x64_bin.zip"));
OutputStream out = new FileOutputStream(new File("D:\\soft\\jdk-14.0.2_windows-x64_bin.zip.bak"))) {
byte[] buff = new byte[1024];
int len = -1;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
// out.flush(); close 方法中会调用flush
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("用时:" + (System.currentTimeMillis() - start));
}
运行结果
用时:1040
可以看到缓冲流比非缓冲流快很多