借助 "118.IO工具类"中的copy设立对照组,测试字节缓冲对性能的提升
package cn.yzy.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class testProductivityOfBufferedStream {
public static void main(String[] args) {
//不使用字节缓冲流
long t1 = System.currentTimeMillis();
copy5("182.181_IO_字节缓冲流.mp4", "copy.mp4");
long t2 = System.currentTimeMillis();
System.out.println(t2 - t1);
//使用字节缓冲流
long t3 = System.currentTimeMillis();
copy6("182.181_IO_字节缓冲流.mp4", "copy.mp4");
long t4 = System.currentTimeMillis();
System.out.println(t4 - t3);
}
public static void copy5(String srcPath, String destPath) {
//创建源
File srcFile = new File(srcPath);
File destFile = new File(destPath);
try(InputStream inputStream = new FileInputStream(srcFile);
OutputStream outputStream = new FileOutputStream(destFile)) {
//分段读取
byte[] flush = new byte[1024];
int len = -1;
while((len = inputStream.read(flush)) != -1) {
outputStream.write(flush, 0, len);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
public static void copy6(String srcPath, String destPath) {
//创建源
File srcFile = new File(srcPath);
File destFile = new File(destPath);
try(InputStream inputStream = new BufferedInputStream(new FileInputStream(srcFile));
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(destFile))) {
//分段读取
byte[] flush = new byte[1024];
int len = -1;
while((len = inputStream.read(flush)) != -1) {
outputStream.write(flush, 0, len);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
发现使用字节缓冲流可以极大的提高数据文件拷贝速度
![](https://i-blog.csdnimg.cn/blog_migrate/25ab61f62f2649ac87a56701381da0e7.png)