从http://www.javabloger.com/article/java-copy-file-performance.html上看到Java拷贝文件的性能中介绍,使用NIO性能会很高,于是用NIO和org.apache.io.FileUtils的copyFile方法做了一下测试对比:
package com.demo.test.file; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * @author user * Description: 操作文件 * 2012-5-5 */ public class HandleFile { /** * Description: 采用java nio里面的FileChannel,非堵塞I/O的文件管道模式,是java 对稍大文件copy 运行效率最高的方式. * @deprecated 如果只是Copy一个小文件或者运行的频率比较低,非NIO方式和NIO方式差不了多少。 * @param fileFromPath * @param fileToPath */ public static void copyFile(String fileFromPath, String fileToPath) { try { // 读取文件创建一个管道 java.nio.channels.FileChannel srcChannel = new java.io.FileInputStream(fileFromPath).getChannel(); // 在管道上创建一个输出的目标地址 java.nio.channels.FileChannel dstChannel = new java.io.FileOutputStream(fileToPath).getChannel(); // 进行文件复制 dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); // 运行复制结束,并且关闭 输入/输出管道流 srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } public static void copyFile2(String srcPath, String destPath){ try { FileUtils.copyFile(new File(srcPath), new File(destPath)); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { long initMils = System.currentTimeMillis(); copyFile("D:\\亚健康学基础(scrom).zip", "D:\\tmp\\scorm.zip"); long endMils = System.currentTimeMillis(); System.out.println("NIO copyFile use time is:" + (endMils - initMils) + "MilliSeconds"); long initMils2 = System.currentTimeMillis(); copyFile("D:\\亚健康学基础(scrom).zip", "D:\\temp\\scorm.zip"); long endMils2 = System.currentTimeMillis(); System.out.println("org.apache.io.FileUtils copyFile use time is:" + (endMils2 - initMils2) + "MilliSeconds"); } }
运行结果如下:
NIO copyFile use time is:1282MilliSeconds org.apache.io.FileUtils copyFile use time is:656MilliSeconds
FileUtils的copyFile比使用NIO快差不多1倍,FileUtils的copyFile源码:
FileInputStream input = new FileInputStream(srcFile); FileOutputStream output = new FileOutputStream(destFile); byte buffer[] = new byte[4096]; long count = 0L; for(int n = 0; -1 != (n = input.read(buffer));) { output.write(buffer, 0, n); count += n; }
可看出copyFile中的buffer数组的容量为4096,所以在操作大文件上更胜一筹。