简介
通过Nio实现高性能文件拷贝。我们需要:Paths、Files、FileChannel实现。
- Paths创建文件路径或者说类似于文件描述符之类的
- Files用于创建新的文件
- FileChannel用于实现文件内容的读取、复制。核心用到java.nio.channels.FileChannel#transferTo。
核心原理
java.nio.channels.FileChannel#transferTo 官方解释: This method is potentially much more efficient than a simple loop that reads from this channel and writes to the target channel. Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.
代码实现
public static void main( String[] args ) throws Exception {
// 获取path
Path path = Paths.get("file/1.txt");
Path path2 = Paths.get("file/3.txt");
// 创建文件
Files.delete(path2);
Files.createFile(path2);
// 打开channel
try(FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ)) {
try(FileChannel fileChannel2 = FileChannel.open(path2, StandardOpenOption.APPEND);) {
// 直接从文件服务器缓存拷贝到channel,无需重复拷贝到jvm中
long result = fileChannel.transferTo(fileChannel.position(), fileChannel.size(), fileChannel2);
System.out.println(result);
// 强制刷盘,保存到文件系统
fileChannel2.force(true);
}catch (Exception e) {
e.printStackTrace();
}
}catch (Exception e) {
e.printStackTrace();
}
}