java复制文件的三种方法

java复制文件的三种方法

Java文件复制,目前我用到了三种方法. 我看到很多文件复制大多是通过byte[]数组的方式,这种方式又麻烦又花时间. 这里介绍另外两种方法: Files工具类和FileChannel的方式. 顺便对三种方式性能做一个对比.

package test.filecopy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import util.TimeUtil;

public class FileCopy {

	public static void main(String[] args) {
		File srcFile = new File("D:/兴风作浪.1080p.HD国语中字无水印[最新电影www.lbldy.com].mp4");
		File destFile = new File("D:/兴风作浪.1080p.HD国语中字无水印[最新电影www.lbldy.com]_copy.mp4");

		TimeUtil.timeStart("copyByArray");
		copyByArray(srcFile, destFile);
		TimeUtil.timeEnd("copyByArray");

		destFile.delete();
		TimeUtil.timeStart("copyByFiles");
		copyByFiles(srcFile, destFile);
		TimeUtil.timeEnd("copyByFiles");

		destFile.delete();
		TimeUtil.timeStart("copyByChannel");
		copyByChannel(srcFile, destFile);
		TimeUtil.timeEnd("copyByChannel");
	}

	private static void copyByArray(File srcFile, File destFile) {
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));) {
			byte[] buffer = new byte[8 * 1024];
			int r = -1;
			while ((r = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, r);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void copyByFiles(File srcFile, File destFile) {
		try {
			Files.copy(Paths.get(srcFile.getAbsolutePath()), Paths.get(destFile.getAbsolutePath()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void copyByChannel(File srcFile, File destFile) {
		try (FileInputStream fis = new FileInputStream(srcFile);
				FileOutputStream fos = new FileOutputStream(destFile);) {
			fis.getChannel().transferTo(0, srcFile.length(), fos.getChannel());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

运行结果:

copyByArray:1366 ms
copyByFiles:463 ms
copyByChannel:453 ms

我在自己电脑上运行,有时候Files工具更快一点,有时候fileChannel更快一点. 自己通过byte[]数组进行拷贝的方式总是最慢的.所以可以根据实际情况,选择files工具类或者fileChannel文件通道的方式进行复制. 我工作的电脑上, fileChannel用时只是byte[]的三分之一.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值