java中复制文件的效率测试

       项目中用到了图片的上传,对于上传过程中,图片的复制项目组用了两种方法,一种是以java的IO流,另外一种是用org.apache.commons.io.FileUtils的工具类,今天我测试了一下,单纯考虑文件的复制效率,apache的工具类的效率是普通io流读取的3倍。

下面是测试源码:

public class ImageTest {

	public static void main(String[] args) throws IOException {
		IOTest();
	}

	public static void fileUtilsTest() throws IOException {
		// 趋近13毫秒后,就保持这个数值
		File srcFile = new File("D:/1.apk");
		File destFile = new File("E:/2.apk");

		long sum = 0;
		for (int i = 0; i < 10; i++) {
			long startTime = System.currentTimeMillis();
			FileUtils.copyFile(srcFile, destFile);
			long endTime = System.currentTimeMillis();
			sum += (endTime - startTime);
		}
		long average = sum / 10;
		System.out.println("耗时" + average + "豪秒");
	}

	public static void IOTest() throws IOException {
		// 50毫秒
		File srcFile = new File("D:/1.apk");
		File destFile = new File("E:/2.apk");

		long sum = 0;
		for (int i = 0; i < 10; i++) {
			long startTime = System.currentTimeMillis();

			InputStream is = new FileInputStream(srcFile);

			// 把图片写入到上面设置的路径里
			OutputStream os = new FileOutputStream(destFile);
			byte[] buffer = new byte[400];
			int length = 0;
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
			is.close();
			os.close();

			long endTime = System.currentTimeMillis();
			sum += (endTime - startTime);
		}
		long average = sum / 10;
		System.out.println("耗时" + average + "豪秒");

	}

}


你可能感兴趣的:(java,复制文件)