NIO简介

nio三大组件

channel,buffer,selector

channel为双向输入输出通道,buffer为缓存,selector为选择器,通过selector来选择线程对出现io操作的channel服务,可有有效的增加线程的工作效率,不用等待某个连接断开才释放线程

bytebuffer

java 复制代码
        //申请空间
        ByteBuffer byteBuffer = ByteBuffer.allocate(100);
        //获取通道
        FileChannel channel = new FileInputStream().getChannel();
        //循环读取
        while (true){
            int read = channel.read(byteBuffer);
            if (read == -1) break;
            //切换读模式
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()){
                byte b = byteBuffer.get();
            }
            //切换写模式
            byteBuffer.clear();
        }

buffer写入数据可以使用

  • 调用 channel 的 read
  • 调用 buffer 自己的 put

buffer读数据有write和get

可以通过这样的方式填充多个buffer,abc为三个buffer对象

java 复制代码
channel.read(new ByteBuffer[]{a, b, c});

同理也可以使用put和write读出写入channel

相关推荐
快乐肚皮7 分钟前
Spring Framework 6:核心升级特性
java·spring
南瓜胖胖8 分钟前
【R语言编程——数据调用】
开发语言·r语言
henreash12 分钟前
C# dll版本冲突解决方案
开发语言·c#
&岁月不待人&21 分钟前
实现弹窗随键盘上移居中
java·kotlin
残*影27 分钟前
Spring Bean的初始化过程是怎么样的?
java·后端·spring
黎䪽圓33 分钟前
【Java多线程从青铜到王者】单例设计模式(八)
java·开发语言·设计模式
Java技术小馆33 分钟前
面试被问 Java为什么有这么多O
java·后端·面试
崔lc1 小时前
Springboot项目集成Ai模型(阿里云百炼-DeepSeek)
java·spring boot·后端·ai
摸鱼仙人~1 小时前
Redux Toolkit 快速入门指南:createSlice、configureStore、useSelector、useDispatch 全面解析
开发语言·javascript·ecmascript