FileChannel只能工作在阻塞模式下
获取FileChannel的方法:
1.通过FileInputStream获取channel只能读。
2.通过FileOutStream获取channel只能写。
3.通过RandomAccessFile是否能读写根据构造RandomAccessFile时的读写模式决定。
4.channel关闭调用close方法,不过调用FileInputStream,FileOutputStream或者RandomAccessFIle的close方法会间接调用channel的close方法
/**
* 基于FileChannel对文件内容进行传输
* 效率高,比文件流输入输出的形式高
* 只要调用了transferTo方法,其底层会使用零拷贝进行优化
* 一次最多传2G数据,大文件可以分多次传输
*/
public static void channelFileTransfer() {
try (FileChannel channel = new FileInputStream("text.txt").getChannel();
FileChannel channel2 = new FileOutputStream(("2.txt")).getChannel()) {
channel.transferTo(0, channel.size(), channel2);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 超过2G文件,分多次传输
*/
public static void channelFileTransferBigFile() {
try (FileChannel channel1 = new FileInputStream("text.txt").getChannel();
FileChannel channel2 = new FileOutputStream("2.txt").getChannel()) {
//left表示剩余多少字节没有传输
long totalSize = channel1.size();
for (long left = totalSize; left > 0; ) {
long actualSize = channel1.transferTo((totalSize - left), left, channel2);
left -= actualSize;
}
} catch (IOException e) {
e.printStackTrace();
}
}