- import java.io.*;
- //用不同方法复制一个8m大小的MP3文件并统计运行时间
- public class Test {
- public static void main(String[] args) throws IOException{
- long startTime = System.currentTimeMillis();
- copyFile_1();
- long endTime = System.currentTimeMillis();
- System.out.println(endTime-startTime+"ms");
-
- startTime = System.currentTimeMillis();
- copyFile_2();
- endTime = System.currentTimeMillis();
- System.out.println(endTime-startTime+"ms");
-
- startTime = System.currentTimeMillis();
- copyFile_3();
- endTime = System.currentTimeMillis();
- System.out.println(endTime-startTime+"ms");
-
- startTime = System.currentTimeMillis();
- copyFile_4();
- endTime = System.currentTimeMillis();
- System.out.println(endTime-startTime+"ms");
- }
-
- //基本读取方式
- public static void copyFile_1() throws IOException {
- //创建IO流对象
- FileInputStream fis = new FileInputStream("D:\\An end,once and for all.mp3");
- FileOutputStream fos = new FileOutputStream("D:\\An end,once and for all1.mp3");
-
- int data = 0;
- //循环读取
- while ((data=fis.read())!=-1) {
- fos.write(data);
- }
- fis.close();
- fos.close();
- }
-
- //在基本读取的方式上定义字节数组作为缓存
- public static void copyFile_2() throws IOException {
- FileInputStream fis = new FileInputStream("D:\\An end,once and for all.mp3");
- FileOutputStream fos = new FileOutputStream("D:\\An end,once and for all2.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 {
- BufferedInputStream fis = new BufferedInputStream(new FileInputStream("D:\\An end,once and for all.mp3"));
- BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\An end,once and for all3.mp3"));
-
- int data = 0;
- while ((data=fis.read())!= -1) {
- fos.write(data);
- }
- fis.close();
- fos.close();
- }
-
- //在使用装饰类也同时使用字节数组缓存
- public static void copyFile_4() throws IOException {
-
- BufferedInputStream fis = new BufferedInputStream(new FileInputStream("D:\\An end,once and for all.mp3"));
- BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\An end,once and for all4.mp3"));
-
- int data = 0;
- byte[] buf = new byte[1024];
- while ((data=fis.read(buf))!= -1) {
- fos.write(buf,0,data);
- }
- fis.close();
- fos.close();
- }
- }
复制代码 运行结果:
62894ms
94ms
109ms
23ms
虽说是有缓存数组,为何第四种方式比其他都快这么多呢?第一种方式为什么会比其他三种方式慢这么多?不解,请指教,先谢谢了 |