Java NIO Channel to Channel Transfers(6)

NIO 通道之间数据传输

  • transferFrom()
  • transferTo()

假如两个Channel中有一个是FileChannel,NIO允许你将数据从其中一个Channel直接传输到另一个Channel。FileChannel有TransferTo() 、TransferFrom()的API可供使用。

TransferFrom()

FileChannel.transfrom():将数据从一个源Channel(比如SocketChannel)传输入一个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
toChannel.transferFrom(fromChannel, position, count);

position、count参数说明了从position处开始向目标文件写入数据,count表示最多传输的字节数。如果源Channel的剩余字节数少于count,传输的字节数就少于请求字节数。

此外,一些SocketChannel实现可能只传输buffer中当前已准备好的数据()。因此,SocketChannel可能不会把请求数量(count)的所有数据从SocketChannel传输到FileChannel。

transferTo()

transferTo() 将FileChannel的数据传输到其他Channel中(比如SocketChannel)。下面是示例:

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
fromChannel.transferTo(position, count, toChannel);

注意下这个例子和上面那个例子有何不同。真正不同的只是方法的调用方而已。其他都相同。

上面说的那个SocketChannel的问题对于同一个transferTo()方法也存在。SocketChannel实现可能会一直从FileChannel传输触发数据直到发送的buffer是空的,然后才停止。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值