NIO非阻塞式IO

BIO 传统的IO,Blocking IO ,阻塞式IO
阻塞式IO,当流进行读写操作时,会阻塞当前线程,当前线程必须等读写完成后,才能进行后面的操作。
相当于在银行排队,如果没有排到,就什么都不能做。
NIO Non-Blocking IO , 非阻塞式IO
JDK1.4出现的,借助于多路复用器,可以实现多个用户同时访问同一个资源,效率更高,编程比较复杂。

使用NIO实现文件的复制:
1) 创建文件输入流和文件输出流
2) 获得文件输入通道和输出通道
3) 创建字节缓冲区
4) 通过输入通道,将数据输入到缓冲区
5) 从缓冲区取出数据,通过输出通道写入文件
从缓冲区取数据前,将缓冲区由写模式转换为读模式,flip()
将缓冲区数据写入文件后,要重置缓冲区,rewind()
6) 关闭流

 @Test
    public void copyNIO(){

        try(
                FileInputStream is=
                        new FileInputStream("E:/code IDEA/second_stage/Java高级集合/IO流/a.txt");
                FileOutputStream os=
                        new FileOutputStream("E:/code IDEA/second_stage/Java高级集合/IO流/b.txt")
                ){
            //获取文件输入通道
            FileChannel isChannel=is.getChannel();
            //获取文件输出通道
            FileChannel osChannel=os.getChannel();
            //获取字节缓冲区
            ByteBuffer flush=ByteBuffer.allocate(1024);
            int len =-1;
            while((len=isChannel.read(flush))!=-1){
                //将缓冲区由写模式改为读模式
                flush.flip();
                osChannel.write(flush);
                //重置缓冲区
                flush.rewind();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

你可能感兴趣的:(java)