NIO

概念

NIO

hsaRemaining()//表明当前缓冲区的位置和限制之间是否尚有元素.

Bio和NIO的比较

Bio用流的方式,Nio用块的方式,块I/O比流IO处理快

Bio是阻塞,Nio非阻塞

BIO是字节流和字符流,Nio是基于channel通道和buffer缓冲进行操作,数据总数通过
缓冲,从缓冲区进入通道,Selector用于监听通道的事件(连接请求,数据到达),因此单线程
就能监听多个通道

NIO 有三大核心部分: Channel(通道)、Buffer(缓冲区)、Selector(选择器)

NIO关系图

  • 每个 Channel 都会对应一个 Buffer。
  • Selector 对应一个线程,一个线程对应多个 Channel(连接)。
  • 该图反应了有三个 Channel 注册到该 Selector //程序
  • 程序切换到哪个 Channel 是由事件决定的,Event 就是一个重要的概念。
  • Selector 会根据不同的事件,在各个通道上切换。
  • Buffer 就是一个内存块,底层是有一个数组。
  • 数据的读取写入是通过 Buffer,这个和 BIO,BIO 中要么是输入流,或者是输出流,不能双向,但是 NIO 的 Buffer 是可以读也可以写,需要 flip 方法切换 Channel 是双向的,可以返回底层操作系统的情况,比如 Linux,底层的操作系统通道就是双向的。

buffer

可读写的内存块

channel

本质上对应流对象,但是比流高级能够读写,通道可以实现异步读写数据
通道可以从缓冲读数据,也可以写数据到缓冲

文件拷贝

File file = new File("d://A.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        //文件拷贝
        FileOutputStream fileOutputStream = new FileOutputStream("D://B.txt");

        FileChannel channel = fileInputStream.getChannel();
        //拷贝文件
        FileChannel channel1 = fileOutputStream.getChannel();
        //设置拷贝文件缓冲
        //ByteBuffer allocate1 = ByteBuffer.allocate(512);
        //文件读取
        ByteBuffer allocate = ByteBuffer.allocate((int) file.length());
        while(true){
            allocate.clear();
            int read = channel.read(allocate);
            if(read==-1){break;}//表示结束
            allocate.flip();
            channel1.write(allocate);
        }
//        channel.read(allocate);
//        System.out.println(new String(allocate.array()));
        fileInputStream.close();
        fileOutputStream.close();
//总的来说就是通道的值要来之于buffer,通过buffer中的flip()来获得channel中的值

Selector

posted @ 2022-12-20 17:27  壹剑霜寒十四州  阅读(17)  评论(0编辑  收藏  举报