NIO - Channel通道 与 Selector选择器

1.2.2 Channel 通道特点:可以同时读写可以异步读写可以从缓冲区读写数据常用ChannelFileChannel – 文件读写DatagramChannel – UDP读写ServerSocketChannel – TCP读写SocketChannel – TCP读写流程​ 当客户端连接服务器时,服务器上的ServerSocketChannel会创建一个与客户端相对应的SocketChannel1.2.2.1 FileChannel读写操作都是通道视角wri
摘要由CSDN通过智能技术生成
1.2.2 Channel 通道

特点:

  • 可以同时读写
  • 可以异步读写
  • 可以从缓冲区读写数据

常用Channel

  • FileChannel – 文件读写
  • DatagramChannel – UDP读写
  • ServerSocketChannel – TCP读写
  • SocketChannel – TCP读写

流程

​ 当客户端连接服务器时,服务器上的ServerSocketChannel会创建一个与客户端相对应的SocketChannel

在这里插入图片描述

1.2.2.1 FileChannel

读写操作都是通道视角

  • write方法 – 缓冲区 == 》通道

输出示例

流程:

  1. 创建输出流
  2. 字符串放入buffer
  3. 从输出流中获取fileChannel
  4. 缓冲区内容写入通道
  5. 通道写入文件
  6. 关闭输出流
public static void main(String[] args) throws  Exception{
   
    String str = "hello world!";
    //创建一个输出流->channel
    FileOutputStream fileOutputStream = new FileOutputStream("F:\\FTHZ\\file01.txt");

    //通过输出流获取对应的 FileChannel
    FileChannel fileChannel = fileOutputStream.getChannel();

    //创建一个缓冲区
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

    //将String写入byteBuffer
    byteBuffer.put(str.getBytes());

    //读写切换
    byteBuffer.flip();

    //写入channel
    fileChannel.write(byteBuffer);
    fileOutputStream.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值