最后更新:2014-07-30
在Java NIO中,你可以直接从一个channel中传输数据到另一个channel,如果channels中的一个是FileChannel。这个FileChannel类有一个transferTo()方法和一个transferFrom方法可以为你做这个事情。
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的字节数量比count数据更少的话,较少的数据就会被传输。
另外,一些SocketChannel的实现可能只是传输在SocketChannel中内部buffer已经准备好的数据--甚至SocketChannel可能不足可用字节的数量。因此,他可能不会传输整个需要的数据(count)从SocketChannel到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的字节直到发送的缓冲区满了,然后就会停下来。
翻译地址:http://tutorials.jenkov.com/java-nio/channel-to-channel-transfers.html