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中