Java NIO中,如果两个通道中有一个是FileChannel,可以直接将数据从一个channel传输到另外一个channel。
- transferFrom
FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中
public void testTransferFrom() throws Exception {
RandomAccessFile srcraf = new RandomAccessFile(
new File("D:/downloads/task.ini"), "rw");
FileChannel srcChannel = srcraf.getChannel();
RandomAccessFile destraf = new RandomAccessFile(
new File("D:/downloads/task2.ini"), "rw");
FileChannel destChannel = destraf.getChannel();
destChannel.transferFrom(destChannel, 0, srcChannel.size());
srcraf.close();
destraf.close();
}
- transferTo
ransferTo()方法将数据从FileChannel传输到其他的channel中
public void testTransferFrom() throws Exception {
RandomAccessFile srcraf = new RandomAccessFile(
new File("D:/360Downloads/task.ini"), "rw");
FileChannel srcChannel = srcraf.getChannel();
RandomAccessFile destraf = new RandomAccessFile(
new File("D:/360Downloads/task2.ini"), "rw");
FileChannel destChannel = destraf.getChannel();
srcChannel.transferTo(0, srcChannel.size(), destChannel);
srcraf.close();
destraf.close();
}
注:以上两个方法中在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。因此,SocketChannel可能不会将请求的所有数据(count个字节)全部传输到FileChannel中