关于文件拷贝效率问题

来源:互联网 发布:xd查询软件 编辑:程序博客网 时间:2024/05/16 12:29

1.不采用缓存,读一次写一次

[java] view plain copy
  1. public static void copy1(String input,String output){  
  2.         FileInputStream fis = null;  
  3.         FileOutputStream fos = null;  
  4.         try {  
  5.             fis = new FileInputStream(new File(input));  
  6.             fos = new FileOutputStream(new File(output));  
  7.             int in = 0;  
  8.             while((in=fis.read())!=-1){  
  9.                 fos.write(in);  
  10. //              System.out.println(in);  
  11.             }  
  12.         } catch (Exception e) {  
  13.             e.printStackTrace();  
  14.         } finally {  
  15.             try {  
  16.                 fis.close();  
  17.                 fos.close();  
  18.             } catch (IOException e) {  
  19.                 e.printStackTrace();  
  20.             }  
  21.         }  
  22.     }  
测试代码:
[java] view plain copy
  1. public static void main(String[] args) {  
  2.     long startTime = System.currentTimeMillis();  
  3.     String input = "d:/linkMap.txt";  
  4.     String output = "d:/output.txt";  
  5.     copy(input,output);  
  6.     long endTime = System.currentTimeMillis();  
  7.     System.out.println((endTime-startTime)+"ms");  
  8. }  
文件大小为16.7MB。运行的时间为:27036ms

2、采用缓存字节数组

[java] view plain copy
  1. public static void copy(String input, String output) {  
  2.         FileInputStream fis = null;  
  3.         FileOutputStream fos = null;  
  4.         try {  
  5.             byte[] buffer = new byte[1024];  
  6.             fis = new FileInputStream(new File(input));  
  7.             fos = new FileOutputStream(new File(output));  
  8.             int len = 0;  
  9.             while ((len = fis.read(buffer)) != -1) {  
  10.                 fos.write(buffer, 0, len);  
  11.             }  
  12.         } catch (Exception e) {  
  13.             e.printStackTrace();  
  14.         } finally {  
  15.             try {  
  16.                 fis.close();  
  17.                 fos.close();  
  18.             } catch (IOException e) {  
  19.                 e.printStackTrace();  
  20.             }  
  21.         }  
  22.     }  
  23.       
同样大小的文件运行时间为360ms。

可见采用缓存来读写文件的效率是惊人的。

原创粉丝点击