Java NIO Channel 与 Channel 之间的传输

在Java NIO中,如果其中一个通道是FileChannel,则可以将数据直接从一个通道传输到另一个通道。 FileChannel类具有transferTo()和transferFrom()方法,该方法可以完成此操作。

 

1.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,告诉目标文件在何处开始写入(位置),以及最大传输多少字节(limit)。如果源通道的字节数少于计数字节,则传输的字节数更少(实际字节数)。

 

2.transferTo()

transferTo()方法从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();

fromChannel.transferTo(position, count, toChannel);

 

该示例与上一个示例相似,唯一真正的区别是调用该方法的是哪个FileChannel对象。

 

SocketChannel的问题也存在于transferTo()方法中。 SocketChannel 的实现只能从FileChannel传输字节,直到发送缓冲区满,然后停止。

 

原文地址: https://www.zhblog.net/go/java/tutorial/java-nio-channel-to-channel?t=612

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值