在Java NIO中,如果其中一個通道是FileChannel,則可以將數據直接從一個通道傳輸到另一個通道。 FileChannel類具有transferTo()和transferFrom()方法,該方法可以完成此操作。
1.transferFrom()
FileChannel.transferFrom()方法將數據從源通道傳輸到FileChannel。這是一個簡單的示例:
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw"); FileChannel fromChannel = fromFile.getChannel(); RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw"); FileChannel toChannel = toFile.getChannel(); long position = 0; long count = fromChannel.size(); toChannel.transferFrom(fromChannel, position, count);
參數position和count,告訴目標文件在何處開始寫入(位置),以及最大傳輸多少字節(limit)。如果源通道的字節數少於計數字節,則傳輸的字節數更少(實際字節數)。
2.transferTo()
transferTo()方法從FileChannel傳輸到其他某個通道。這是一個簡單的示例:
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw"); FileChannel fromChannel = fromFile.getChannel(); RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw"); FileChannel toChannel = toFile.getChannel(); long position = 0; long count = fromChannel.size(); fromChannel.transferTo(position, count, toChannel);
該示例與上一個示例相似,唯一真正的區別是調用該方法的是哪個FileChannel對象。
SocketChannel的問題也存在於transferTo()方法中。 SocketChannel 的實現只能從FileChannel傳輸字節,直到發送緩衝區滿,然後停止。
原文地址: https://www.zhblog.net/go/java/tutorial/java-nio-channel-to-channel?t=612