
JAVA NIO Scatter/Gather(矢量IO)
发布日期:2021-05-09 05:38:08
浏览次数:16
分类:博客文章
本文共 1562 字,大约阅读时间需要 5 分钟。
矢量IO=Scatter/Gather:
在多个缓冲区上实现一个简单的IO操作。减少或避免了缓冲区拷贝和系统调用(IO)
write:Gather
数据从几个缓冲区顺序抽取并沿着通道发送,就好比全部缓冲区全部连接起来放入一个大的缓冲区进行发送,缓冲区本身不具备gather能力。
read:Scatter
从通道读取的数据会按顺序散布到多个缓冲区,直到缓冲区被填满或者通道数据读完。
Gather:
Scatter:
示例代码:
/** * channel Gather/Scatter */ public static void channelGatherScatter(){ ByteBuffer head = ByteBuffer.allocate(4); ByteBuffer body = ByteBuffer.allocate(100); RandomAccessFile afile = null; RandomAccessFile bfile = null; ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); try { afile = new RandomAccessFile("hello.txt", "r"); bfile = new RandomAccessFile("hehe.txt", "rw"); readWriteLock.readLock().lock(); FileChannel fileChannel = afile.getChannel(); ByteBuffer[] buffers = {head, body}; while (fileChannel.read(buffers) != -1){ } head.flip(); body.flip(); System.out.println(new String(head.array())); System.out.println(new String(body.array())); readWriteLock.readLock().unlock(); fileChannel.close(); afile.close(); readWriteLock.writeLock().lock(); FileChannel bfileChannel = bfile.getChannel(); while (bfileChannel.write(buffers) > 0){ } readWriteLock.writeLock().unlock(); bfileChannel.close(); bfile.close(); }catch (Exception e){ e.printStackTrace(); } }
带offset、length参数重载read write方法,指明从那个buffer开始,共使用多少个buffer。
发表评论
最新留言
关注你微信了!
[***.104.42.241]2025年04月20日 21时20分31秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
python中列表 元组 字典 集合的区别
2019-03-07
python struct 官方文档
2019-03-07
Android DEX加固方案与原理
2019-03-07
Android Retrofit2.0 上传单张图片和多张图片
2019-03-07
iOS_Runtime3_动态添加方法
2019-03-07
Leetcode第557题---翻转字符串中的单词
2019-03-07
Problem G. The Stones Game【取石子博弈 & 思维】
2019-03-07
Unable to execute dex: Multiple dex files
2019-03-07
Java多线程
2019-03-07
Unity监听日记
2019-03-07
openssl服务器证书操作
2019-03-07
expect 模拟交互 ftp 上传文件到指定目录下
2019-03-07
linux系统下双屏显示
2019-03-07
PDF.js —— vue项目中使用pdf.js显示pdf文件(流)
2019-03-07
我用wxPython搭建GUI量化系统之最小架构的运行
2019-03-07
我用wxPython搭建GUI量化系统之多只股票走势对比界面
2019-03-07
selenium+python之切换窗口
2019-03-07
重载和重写的区别:
2019-03-07
搭建Vue项目步骤
2019-03-07
账号转账演示事务
2019-03-07