Java Nio 六、Java NIO通道到通道的传输

最后更新: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值