什么是NIO?

1, BIO(Blocking IO)传统的IO流,同步阻塞式IO,效率低,需要大量线程,编程简单

2,NIO(NonBlocking IO)java1.4出现的新的IO方式,同步非阻塞式IO,效率高,不需要大量线程,编程复杂

3,AIO(Asynchronize IO) 异步非阻塞式IO,效率高,编程复杂

举个例子:
烧开水

BIO 等在旁边什么都不干,直到水烧开

​NIO 可以做其它事情,需要隔一段时间过来看看

​AIO 可以做其它事情,水烧开会自动通知他

NIO的API:

​传统的IO面向的是流 ​
NIO面向的是块 ​
Buffer 缓冲区 ​
Channel 通道 ​
Selector 多路复用器

在这里插入图片描述
代码实现:

public class NioTest {

    public static void copy(String source,String target){
        //创建文件流
        try (FileInputStream in = new FileInputStream(source);
             FileOutputStream out = new FileOutputStream(target)
        ){
            //创建文件通道
            FileChannel inChannel = in.getChannel();
            FileChannel outChannel = out.getChannel();
            //创建文件缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(100);
            int len = 0;
            //数据读出来写入到buffer中
            while ((len = inChannel.read(buffer)) != -1){
                //将buffer的状态,从写状态切换到读状态
                buffer.flip();
                //将buffer的数据写到输出通道
                outChannel.write(buffer);
                //清除原来的数据
                buffer.rewind();
            }
            inChannel.close();
            outChannel.close();

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

    public static void main(String[] args) {
        copy("C:\\Users\\admin\\Desktop\\杂物.txt","C:\\Users\\admin\\Desktop\\杂物1111.txt");
    }
}

运行效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值