在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中FileChannel的transferTo和transferFrom方法,用于实现不同Channel之间的数据转换。通过实例演示了如何将数据从一个Channel传输到另一个Channel,包括从FileChannel到FileChannel及反之的数据传输过程。
368

被折叠的 条评论
为什么被折叠?



