问题:
分别使用文件流和缓冲流复制一个长度大于100MB的视频文件,并观察效率的差异。
代码:
文件流:
import java.io.*;
public class IO2 {
public static void main(String[] args) throws IOException {
//创建输入流和输出流
InputStream fis = new FileInputStream(new File("C:\\Users\\48393\\IdeaProjects\\javaOOP\\IOtest\\src\\homework\\IO2.mp4"));
OutputStream fos = new FileOutputStream("C:\\Users\\48393\\IdeaProjects\\javaOOP\\IOtest\\src\\homework\\IO21.mp4");
//使用输入流和输出流复制文件
long start=System.nanoTime();
byte [] buf = new byte[1024];
int len = fis.read(buf);
while(len!=-1){
//写
fos.write(buf, 0, len);
//读
len = fis.read(buf);
//System.out.println(len);
}
long end=System.nanoTime();
double time = (end - start) / 1000000000.0 ; // 将纳秒转换为秒
System.out.println("复制耗时:"+time + "s");
//关闭输入流和输出流
fis.close();
fos.close();
System.out.println("完成");
}
}
缓冲流:
import java.io.*;
public class IO21 {
public static void main(String[] args) throws IOException {
//创建输入流和输出流
InputStream fis = new FileInputStream(new File("C:\\Users\\48393\\IdeaProjects\\javaOOP\\IOtest\\src\\homework\\IO2.mp4"));
OutputStream fos = new FileOutputStream("C:\\Users\\48393\\IdeaProjects\\javaOOP\\IOtest\\src\\homework\\IO22.mp4");
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
//使用输入流和输出流复制文件
long start=System.nanoTime();
byte [] buf = new byte[1024];
int len = bis.read(buf);
while(len!=-1){
//写
bos.write(buf, 0, len);
//读
len = bis.read(buf);
}
long end=System.nanoTime();
double time = (end - start) / 1000000000.0 ; // 将纳秒转换为秒
System.out.println("复制耗时:"+time + "s");
//关闭输入流和输出流
bis.close();
bos.close();
System.out.println("完成");
}
}