首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >netty前传-NIO中缓冲buffer-channel

netty前传-NIO中缓冲buffer-channel

作者头像
用户1418372
发布2018-10-25 15:04:34
4310
发布2018-10-25 15:04:34
举报
文章被收录于专栏:清晨我上码清晨我上码

前面已经基本上介绍过buffer如何通过channel进行读写操作,这里要补充说明的是channel还能够读取写入多个buffer

  • 注意这里说的读写对象是针对buffer而言,对channel而言则相反
  1. 通过channel写入数据到多个buffer(针对buffer而言是写入操作)

图片.png

 //获取连接通道
            FileChannel fileChannel = randomAccessFile.getChannel();
            //初始化一个缓冲区,大小为1024byte
            ByteBuffer buf01 = ByteBuffer.allocate(128);
            ByteBuffer buf02 = ByteBuffer.allocate(1024);
            ByteBuffer[] bufferArray = { buf01, buf02 };
            fileChannel.read(bufferArray);

针对上面这段代码表示,channel中的数据会根据数组的顺序,先写到buf01中,当buf01写完128个字节后,仍然有数据则会继续写入buf02。这样可以为我们方便的将我们需要的数据隔离。

  1. 将通过channel读取多个buffer数据到channel(针对buffer是读取操作)

图片.png

//初始化一个缓冲区,大小为1024byte
            ByteBuffer buf01 = ByteBuffer.allocate(128);
            buf01.put((byte) 2);
            ByteBuffer buf02 = ByteBuffer.allocate(1024);
            buf01.put((byte) 122);
            ByteBuffer[] bufferArray = { buf01, buf02 };
            fileChannel.write(bufferArray);

同理针对上面的代码,channel会根据数组顺序读取buf01和buf02的可读数据,注意读取的数据量为buffer的限制大小,比如buf01只有一个字节大小,则只会读取一个字节的数据接着读取buf02的数据


FileChannel之间的转换

FileChannel可以直接将数据从一个通道传输到另一个通道。 操作这个是通过FileChannel类有中的transferTo()和transferFrom()方法。下面代码片段演示:

 //源通道
            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();
//transferFrom将源通道数据传入到目的通道中,position标记传输的起始位置,count表示传输的大小
            toChannel.transferFrom(fromChannel, position, count);
//transferTo方法和上面的唯一区别,就是调用的对象不同(上面方法和下面两个处理等价)
      fromChannel.transferTo(position, count, toChannel);
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.10.17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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