试了下用FileChanel.transferTo复制一个4G多的文件,和用传统IO复制,发现FileChannel居然并没有更快。这是为什么呢?代码如下:
package com.example.demo.nio;
import org.springframework.util.StopWatch;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.*;
public class FileChannelTest {
public static void main(String[] args) {
String fromPath = "D:\\softpackages\\CentOS-7-x86_64-DVD-2009.iso";
String toPath = "D:\\softpackages\\CentOS-7-x86_64-DVD-2009_back.iso";
// String fromPath = "D:\\softpackages\\mysql-8.0.27-winx64.zip";
// String toPath = "D:\\softpackages\\mysql-8.0.27-winx64_back.zip";
Path from = Paths.get(fromPath);
Path to = Paths.get(toPath);
StopWatch stopWatch = new StopWatch();
stopWatch.start("传统方法复制文件");
traditional(from, to);
stopWatch.stop();
stopWatch.start("nio复制文件");
fileChannel(from, to);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
}
private static void fileChannel(Path from, Path to) {
try(FileChannel channel = FileChannel.open(from, StandardOpenOption.READ);
FileChannel toChannel = FileChannel.open(to, StandardOpenOption.WRITE)){
long size = channel.size();
long left = size;
while(left>0){
left-=channel.transferTo(size-left,left,toChannel);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void traditional(Path from, Path to) {
try(BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(from));
BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(to))){
byte[] buffer = new byte[1024*1024*200];
int read = inputStream.read(buffer);
while(read!=-1){
outputStream.write(buffer,0,read);
read = inputStream.read(buffer);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
运行结果显示FileChannel并没有更快。调换顺序,影响不大。
换200+M的文件试了下,fileChannel有明显优势
不懂为什么大文件(G级),用FIleChannel并没有优势,有大佬能解释吗?