在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