import java.io.*;
//用不同的方法复制文件并统计执行时间
public class CopyFile_2 {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
copyFile_1();
long end = System.currentTimeMillis();
System.out.println(end-start+"毫秒");
start = System.currentTimeMillis();
copyFile_2();
end = System.currentTimeMillis();
System.out.println(end-start+"毫秒");
start = System.currentTimeMillis();
copyFile_3();
end = System.currentTimeMillis();
System.out.println(end-start+"毫秒");
start = System.currentTimeMillis();
copyFile_4();
end = System.currentTimeMillis();
System.out.println(end-start+"毫秒");
}
//基本读取方式
public static void copyFile_1() throws IOException {
//创建IO流对象
FileInputStream fis = new FileInputStream("D:\\Kugou\\in\\xuewei - jia.mp3");
FileOutputStream fos = new FileOutputStream("jia1.mp3");
int data = 0;
//循环读写数据
while ((data=fis.read())!=-1) {
fos.write(data);
}
fis.close();
fos.close();
}
//在基本读取的方式定义字节数组作为缓冲
public static void copyFile_2() throws IOException {
//创建IO流对象
FileInputStream fis = new FileInputStream("D:\\Kugou\\in\\xuewei - jia.mp3");
FileOutputStream fos = new FileOutputStream("jia2.mp3");
byte[] buf = new byte[1024];
int len = 0;
//循环读写数据
while ((len=fis.read(buf))!=-1) {
fos.write(buf,0,len);
}
fis.close();
fos.close();
}
//通过包装类来读取和写入文件
public static void copyFile_3() throws IOException {
//创建IO流对象
BufferedInputStream fis = new BufferedInputStream(new FileInputStream("D:\\Kugou\\in\\xuewei - jia.mp3"));
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("jia3.mp3"));
int data = 0;
//循环读写数据
while ((data=fis.read())!= -1) {
fos.write(data);
}
fis.close();
fos.close();
}
//在使用包装类也同时使用数组缓冲
public static void copyFile_4() throws IOException {
//创建IO流对象
BufferedInputStream fis = new BufferedInputStream(new FileInputStream("D:\\Kugou\\in\\xuewei - jia.mp3"));
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("jia4.mp3"));
int data = 0;
byte[] buf = new byte[1024];
//循环读写数据
while ((data=fis.read(buf))!= -1) {
fos.write(buf,0,data);
}
fis.close();
fos.close();
}
}
运行结果
59578毫秒
79毫秒
89毫秒
24毫秒
//为何第四种方式比较块呢,而且在包装类中已经封装得有数组,为何还需要在外面再定义一个数组呢?第一种方式为什么会比其他三种方式慢这么多?不解,请指教,先谢谢了。 |