NIO学习

NIO学习

N IO简介

NIO与IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区,基于通道

的IO操作,NIO能以更高效的方式读写操作。

在这里插入图片描述

NIO的工作原理

NIO有缓冲区(buffer一个数据容器)和通道(Channel)

简而言之好比 运送一批货物,通道是车道,缓冲区是车厢,货物的到达就是数据的传递

在这里插入图片描述

NIO读写数据
  String s="sgsgs";
        ByteBuffer allocate = ByteBuffer.allocate(10);
        //放入数据
       allocate.put(s.getBytes());
       //读取数据
        allocate.flip();
        byte[] bytes = new byte[allocate.limit()];
        //读取数据
        allocate.get(bytes,0,2);
        System.out.println(allocate.position());
        //标记
        allocate.mark();
        //再次读取数据
        allocate.get(bytes,2,3);
        //回到上次指针标记的position位置用 reset()方法
        allocate.reset();
    

用NIO复制数据方式
  • 方式一

​ (1)用fileOutputstream和FileInputStream读取

​ (2)构建getChannel通道

FileInputStream in = new FileInputStream("file.txt");
FileOutputStream out = new FileOutputStream("file2.txt");
//构建缓冲区通道
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (inChannel.read(byteBuffer)!=-1){
    byteBuffer.flip();
    outChannel.write(byteBuffer);
    //清空缓冲区
    byteBuffer.clear();
}
inChannel.close();
outChannel.close();
in.close();
out.close();
  • 方式二

    通过FileChannel中的静态方法 open()可以打开一个通道

      FileChannel in= FileChannel.open(Paths.get("file.txt"), StandardOpenOption.READ);
            FileChannel out = FileChannel.open(Paths.get("file2.ts"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            ByteBuffer allocate = ByteBuffer.allocate(1024 * 1024);
            while (in.read(allocate)!=-1){
                //切换读取模式
                allocate.flip();
                out.write(allocate);
                allocate.clear();
            }
            in.close();
            out.close();FileChannel in= FileChannel.open(Paths.get("歌曲串烧.mp3"), StandardOpenOption.READ);
    FileChannel.open(Paths.get("file2.ts"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值