java nio/io复制文件 工具类实现。
package com.tencentyun.util;
import org.junit.Test;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioFileUtils {
public void nioCopyTo(String filePath, String destFilePath) {
long startTime = System.currentTimeMillis(); //获取开始时间
try (FileInputStream fileInputStream = new FileInputStream(new File(filePath));
FileOutputStream fileOutputStream = new FileOutputStream(new File(destFilePath));
FileChannel in = fileInputStream.getChannel();//得到对应的文件通道
FileChannel out = fileOutputStream.getChannel();//得到对应的文件通道
)
{
ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 1024);//缓冲区大小
while ((in.read(byteBuffer)) != -1) {
//切换读取模式
byteBuffer.flip();
out.write(byteBuffer);
byteBuffer.clear();
}
} catch (Exception e) {
System.out.println(e);
}
long endTime = System.currentTimeMillis(); //获取结束时间
System.out.println("nio 复制文件 程序运行时间: " + (endTime - startTime) + "ms");
}
public void copyTo(String filePath, String destFilePath) {
long startTime = System.currentTimeMillis(); //获取开始时间
try (
InputStream fileInputStream = new FileInputStream(new File(filePath));
OutputStream fileOutputStream = new FileOutputStream(new File(destFilePath));
) {
int len = 0;
byte[] bytes = new byte[1024 * 1024];
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis(); //获取结束时间
System.out.println("io 复制文件 程序运行时间: " + (endTime - startTime) + "ms");
}
@Test
public void testCopyFile() {
nioCopyTo("D:\\Download\\ideaIU-2018.3.6.exe", "D:\\temp\\ideaIU-NIO.exe");
copyTo("D:\\Download\\ideaIU-2018.3.6.exe", "D:\\temp\\ideaIU-IO.exe");
}
}
文 件:600M
复制时间:NIO 耗时:327ms ,IO耗时:667ms