Java NIO Channel to Channel Transfers

80 阅读1分钟

在Java NIO 你可以直接从一个channel传数据到另一个channel,如果其中一个channel是FileChannel。FileChannel 类有一个transferTo()和transferFrom()可以完成这个操作。

transferFrom()

FileChannel.transFrom()方法从一个源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小于count字节,传递的数据更少。

另外说一句,一些SocketChanel实现只在SocketChannel已经在它内部准备好buffer的时候才能传递数据-即使SocketChannel后面也许还有更多的数据。如此,它也许不会将从SocketChannel请求的全部数据(count)到FileChannel。

transferTo()

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

注意,这个跟前面的例子非常相似。唯一的区别在FileChannel对象在哪里调用。其余都是一样的。

SocketChannel的问题同时也存在于transferTo()方法。SocketChannel的实现上会一直从FileChannel传递字节直到发送buffer满为止,然后才停止。