6 Java NIO Channel to Channel Transfers-翻译

在Java NIO中,如果其中的一个通道是FileChannel,你可以直接从一个通道向另一个通道直接转换数据。FileChannel有一个transferTo和transferFrom方法来实现这个功能。

transferFrom()

FileChannel.transferFrom()方法将另一个通道的数据转换到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分别表明目标文件从哪里开始写,最大需要转换的字节数。如果源channel的长度小于count,则取小的那个。

另外,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。因此,SocketChannel可能不会将请求的所有数据(count个字节)全部传输到FileChannel中。

transferTo()

transferTo方法负责将FileChannel转换到其他Channel.下面是一个简单的例子。

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt","rw");
FileChannel fromChannel = fromFile.getChannle();

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会一直传输数据直到目标buffer被填满。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值