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

相关推荐
百***464516 分钟前
Java进阶-在Ubuntu上部署SpringBoot应用
java·spring boot·ubuntu
serve the people23 分钟前
Prompts for Chat Models in LangChain
java·linux·langchain
一叶飘零_sweeeet1 小时前
不止于 API 调用:解锁 Java 工具类设计的三重境界 —— 可复用性、线程安全与性能优化
java·工具类
惊讶的猫1 小时前
LSTM论文解读
开发语言·python
獨枭2 小时前
C# 本地项目引用失效与恢复全攻略
开发语言·c#·visual studio
国服第二切图仔2 小时前
Rust开发之Trait 定义通用行为——实现形状面积计算系统
开发语言·网络·rust
mjhcsp2 小时前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
A阳俊yi2 小时前
Spring Data JPA
java·开发语言
小王不爱笑1322 小时前
Spring AOP(AOP+JDBC 模板 + 转账案例)
java·后端·spring