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[]的三分之一.