前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java NIO-5.通道之间的数据传输

Java NIO-5.通道之间的数据传输

作者头像
悠扬前奏
发布2019-05-30 20:17:55
6630
发布2019-05-30 20:17:55
举报

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

transferFrom

FileChannel.transferFrom()方法可以将数据从源通道传输到FileChannel中,一个简单例子如下:

代码语言:javascript
复制
RandomAccessFile fromFile = new RandomAccessFile("./data/from-data.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("./data/to-data.txt", "rw");
FileChannel toChannel = toFile.getChannel();

long position = 0;
long count = fromChannel.size();

toChannel.transferFrom(fromChannel, position, count);

position和count参数,指定目标文件写入的位置(position),和传输的最大字节数(count)。如果源文件字节数小于count,传输的就少一些。 另外,一些SocketChannel的实现可能仅传输当前网络上所属缓冲区已经准备好的数据,哪怕SocketChannel将来可能有更多的可用数据。因此,从SocketChannel传输到FileChannel中的数据可能不是完整的。

transferTo()

transferTo()方法将FileChannel中的数据传输到其他的通道中,例如:

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

注意本例和前例的类似处。唯一不同的地方在于FileChannel对象调用的方法不同,其他的是一样的。

和SocketChannel存在的问题transferTo()方法也有。SocketChannel的实例可能从FileChannel中传输字节的时候,发送的缓冲区一满就停止。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.06.02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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