分别使用字节流和字节缓冲流复制文本文件/图片/视频,并记录其所用时间(毫秒)
package myByteStream;
import java.io.*;
public class Test1 {
public static void main(String[] args) throws IOException {
//记录开始时间
long startTime = System.currentTimeMillis();
//复制文本文件
//method1();//共耗时:578
//method2();//共耗时:32
//复制图片
//method3();//共耗时:531
//method4();//共耗时:46
//复制视频
method5();//共耗时:6406//共耗时:3827//共耗时:2485
//method6();//共耗时:15243//共耗时:7590//共耗时:8563
//记录结束时间
long endTime = System.currentTimeMillis();
System.out.println("共耗时:" + (endTime - startTime));
}
/* private static void method6() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\b.avi"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\ba.avi"));
byte[] bys = new byte[2048];
int len;
while((len = bis.read(bys)) != -1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}*/
private static void method5() throws IOException {
FileInputStream fis = new FileInputStream("E:\\b.avi");
FileOutputStream fos = new FileOutputStream("E:\\abc.avi");
byte[] bys = new byte[2048];
int len ;
while((len = fis.read(bys)) != -1){
fos.write(bys,0,len);
}
fos.close();
fis.close();
}
/*private static void method4() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\\\a.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\b.jpg"));
byte[] bys = new byte[1024];
int len;
while((len = bis.read(bys)) != -1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}*/
/*private static void method3() throws IOException {
FileInputStream fis = new FileInputStream("E:\\a.jpg");
FileOutputStream fos = new FileOutputStream("E:\\b.jpg");
byte[] bys = new byte[1024];
int len ;
while((len = fis.read(bys)) != -1){
fos.write(bys,0,len);
}
fos.close();
fis.close();
}*/
//字节缓冲流一次读写一个字节数组
/*private static void method2() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\file\\test.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\file\\b.txt"));
byte[] bys = new byte[1024];
int len;
while((len = bis.read(bys)) != -1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}*/
/*// 基本字节流一次读写一个字节数组
private static void method1() throws IOException {
FileInputStream fis = new FileInputStream("E:\\file\\test.txt");
FileOutputStream fos = new FileOutputStream("E:\\file\\b.txt");
byte[] bys = new byte[1024];
int len ;
while((len = fis.read(bys)) != -1){
fos.write(bys,0,len);
}
fos.close();
fis.close();
}*/
}
在复制文本、图片时,从运行结果,我们不难看出,使用字节缓冲流比使用字节流复制的效率要高许多,原因:copyFile的操作中,我们的写法是,在while中,读一次byte[],立即写入到文件中。
但是用BufferedInputStream,就可以将多次读取到的数据,先放进缓冲中,也就是内存中,当缓冲达到设置的大小时,就会写入到文件一次。
这样就减少了写入文件的次数,提高了速度。
这样一解释,我们可以理解为,程序用空间换时间,目的是提高速度。
按理说,复制视频也是一样的道理,但运行结果却告诉我很多事并不是想当然的。我多次复制视频(18.9M)进行两者的比较,发现使用字节缓冲流要比使用字节流所花的时间超出两倍多!!!而且这不是偶然事件。至于原因我还没找到,等后续.......
同样的代码,我拿到同学的电脑上运行,发现是缓冲流要比字节流快很多!所以出现我上面的情况,应该与电脑配置有关——内存大小、多核或单核CPU等等。
解决方案:可以拿一个大一点的视频再试试;或者换一台配置好一些的电脑。