- NIO是一种基于通道和缓冲区的io方式,它可以使用native函数直接分配堆外内存,然后通过一个存储在java堆里面的DirectByteBuffer;
- 对象作为这块内存的直接引用进行操作。这样能在一些场景显著提高性能,因为避免了在java堆和native堆中来回复制数据。
- transferTo()将数据从一个通道传输到其他通道;
package com.xxx;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class demo005_fileCopy {
public static void main(String[] args) throws IOException {
File inFile = new File("C:\\Users\\user\\Downloads\\12.txt");
File outFile = new File("C:\\Users\\user\\Downloads\\12_copy.txt");
fileCopy(inFile, outFile);
}
public static void fileCopy(File in, File out) throws IOException {
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
int maxCount = (64*1024*1024) -(32*1024*1024);
long size = inChannel.size();
long position = 0;
while (position< size){
position+= inChannel.transferTo(position, maxCount, outChannel);
}
System.out.println("coty success.");
} finally {
if (inChannel!=null) {
inChannel.close();
}
if (outChannel!=null) {
outChannel.close();
}
}
}
}