IO流中当处理大文件时,为提高速度,可以应用缓存流:BufferedInputStream和BufferedOutputStream
示例
BufferedInputStream带来的速度提升,准备文件几十兆,太小看不出明显效果,太大等的时间太长了。我准备的是个16m的视频文件。
public static void copyFile(String src, String dist) throws IOException {
long start2 = System.currentTimeMillis();
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dist);
byte[] buffer = new byte[20 * 1024];
int cnt;
/**
* read()最多读取buffer.length个字节
* 返回的实际读取的个数
* 返回-1的时候表示读到eof,即文件尾
*/
while ((cnt = in.read(buffer)) != -1) {
out.write(buffer, 0, cnt);
}
in.close();
out.close();
long end2 = System.currentTimeMillis();
System.out.println("不用缓存类时用的时间:" + (end2 - start2));
long start3 = System.currentTimeMillis();
FileInputStream in2 = new FileInputStream(src);
FileOutputStream out2 = new FileOutputStream(dist);
BufferedInputStream bis = new BufferedInputStream(in2);
BufferedOutputStream bos = new BufferedOutputStream(out2);
byte[] buffer2 = new byte[20 * 1024];
int cnt2;
while ((cnt2 = bis.read(buffer2)) != -1) {
bos.write(buffer2, 0 , cnt2);
}
in2.close();
out2.close();
bis.close();
bos.close();
long end3 = System.currentTimeMillis();
System.out.println("缓存类时用的时间:" + (end3 - start3));
}
通过输出的时间对比,可以明显得到缓存流更快,另外byte[]的大小也影响速度,越大越快。