Java NIO 系列学习 06 - Channel to Channel Transfers

在Java NIO中,如果有两个Channel且其中一个是FileChannel时,我们可以传递数据从一个channel到另一个channel。FileChannle类提供了transferTo()transferFrom()方法来操作。

transferFrom()

FileChannel.transferFrom()方法可以实现从一个源Channel到当前Channel的数据传递。
下面是一段示例代码:

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

参数positioncount, 决定了toChannel的写入位置和传递数据的大小。如果fromChannel的实际大小比count小,则只会传递实际大小的数据。

另外,如果fromChannelSocketChannel的实现类,则只会传递已经在内部缓存区准备好的数据,可能不会将所有(count)数据都传递过来。

transferTo()

FileChannel.transferTo() 方法可以实现数据从FileChannel到另外一个channel的传递。
下面是一段示例代码:

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

transferFrom()很相似,另外,对于SocketChannel实现类的问题同样存在。

参考

  1. Java NIO Channel to Channel Transfers