前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java NIO 系列学习 06 - Channel to Channel Transfers

Java NIO 系列学习 06 - Channel to Channel Transfers

作者头像
许杨淼淼
发布2019-12-29 19:59:55
5810
发布2019-12-29 19:59:55
举报
文章被收录于专栏:醉程序醉程序

在Java NIO中,如果有两个Channel且其中一个是FileChannel时,我们可以传递数据从一个channel到另一个channel。FileChannle类提供了transferTo()transferFrom()方法来操作。

transferFrom()

FileChannel.transferFrom()方法可以实现从一个源Channel到当前Channel的数据传递。 下面是一段示例代码:

代码语言:javascript
复制
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);

参数positioncount, 决定了toChannel的写入位置和传递数据的大小。如果fromChannel的实际大小比count小,则只会传递实际大小的数据。

另外,如果fromChannelSocketChannel的实现类,则只会传递已经在内部缓存区准备好的数据,可能不会将所有(count)数据都传递过来。

transferTo()

FileChannel.transferTo() 方法可以实现数据从FileChannel到另外一个channel的传递。 下面是一段示例代码:

代码语言:javascript
复制
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);

transferFrom()很相似,另外,对于SocketChannel实现类的问题同样存在。

参考

  1. Java NIO Channel to Channel Transfers
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年4月23日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • transferFrom()
  • transferTo()
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档