【译】Java NIO Channel to Channel Transfers

半城伤御伤魂 提交于 2020-01-07 17:51:23

在Java NIO中可以直接从一种channel转化成另一种channel。例如,FileChannel类有一个transferTo的方法和一个transferFrom的方法,都可以做channel转化。

transferFrom()

FileChannel.transferFrom()可以把源channel转发成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,说明了目标文件从哪里开始写(position),最多有多少字节可以传输(count)。如果源channel的bytes数量少于count,则传输的数据就更少。

另外,一些SocketChannel的实现可能只传输SocketChannel内部已经准备好了的数据,即便SocketChannel可能之后会收到很多数据也不行。因此,当SocketChannel转化成FileChannel时,它可能不会传输要求大小(count)的数据。

transferTo()

这个方法和之前的转换方向相反,例如:

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);

这和上一个很像,唯一的不通就是调用转换方法的对象是谁。剩下的都一样。

 

下一篇:【译】Java NIO Selector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!