NIO(New IO)

NIO(New IO)

  1. 概述:
    Java NIO ( New IO )是从 Java 1.4 版本开始引入的一个新的 IO API ,
    可以替代标准的 Java IO API 。NIO 与原来的 IO 有同样的作用和目的,但是使用的方式完全不同, NIO 支持面向缓冲区的、基于通道的 IO 操作。 NIO 将以更加高效的方式进行文件的读写操作。
  2. Java IO 与 NIO 的区别
IONIO
面向流(StreamOriented)面向缓冲区(BufferOriented)
阻塞IO(BlockingIO) BIO非阻塞IO(NonBlockingIO)
(无)选择器(Selectors)
  1. 通道(Channel)与缓冲区(Buffer
    通道表示打开到 IO 设备 ( 例如:文件、套接字 ) 的连接。若需要使用 NIO 系统,需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区,对数据进行处理。

    Channel 负责传输, Buffer 负责存储

    缓冲区( Buffer ):一个用于特定基本数据类型的容器。由 java.nio 包定义的,所有缓冲区都是 Buffer 抽象类的子类。
    Java NIO 中的 Buffer 主要用于与 NIO 通道进行交互,数据是从通道读入缓冲区,从缓冲区写入通道中的。

    Buffer 就像一个数组,可以保存多个相同类型的数据。
    根据数据类型不同 (boolean 除外 ) ,有以下 Buffer 常用子类:
    ByteBuffer
    CharBuffer
    ShortBuffer
    IntBuffer
    LongBuffer
    FloatBuffer
    DoubleBuffer

  2. 缓存区的基本属性:

    1. 容量 (capacity) : 表示 Buffer 最大数据容量,缓冲区容量不能为负,并且创
      建后不能更改。
    2. 限制 (limit) : 第一个不应该读取或写入的数据的索引,即位于 limit 后的数据
      不可读写。缓冲区的限制不能为负,并且不能大于其容量。
    3. 位置 (position) : 下一个要读取或写入的数据的索引。缓冲区的位置不能为
      负,并且不能大于其限制
    4. 标记 (mark) 与重置 (reset) : 标记是一个索引,通过 Buffer 中的 mark() 方法
      指定 Buffer 中一个特定的 position ,之后可以通过调用 reset() 方法恢复到这
      个 position.

    PS:0 <= mark <= position <= limit <= capacity

  3. 缓冲区常用方法

方法描述
Buffer clear()清空缓冲区并返回对缓冲区的引用
Buffer flip**()将缓冲区的界限设置为当前位置,并将当前位置充值为0
int capacity()返回Buffer的capacity大小
boolean hasRemaining()判断缓冲区中是否还有元素
int limit()返回Buffer的界限(limit)的位置
Buffer limit(intn)将设置缓冲区界限为n,并返回一个具有新limit的缓冲区对象
Buffer mark()对缓冲区设置标记
int position()返回缓冲区的当前位置position
Buffer position(int n)将设置缓冲区的当前位置为n,并返回修改后的Buffer对象
int remaining()返回position和limit之间的元素个数
Buffer reset()将位置position转到以前设置的mark所在的位置
Buffer rewind()将位置设为为0,取消设置的mark

操作数据:
获取 Buffer 中的数据
get() :读取单个字节
get(byte[] dst) :批量读取多个字节到 dst 中
get(int index) :读取指定索引位置的字节 ( 不会移动 position)
放入数据到 Buffer 中
put(byte b) :将给定单个字节写入缓冲区的当前位置
put(byte[] src) :将 src 中的字节写入缓冲区的当前位置
put(int index, byte b) :将指定字节写入缓冲区的索引位置 ( 不会移动 position)

  1. 例:
import java.nio.ByteBuffer;

public class Test {
    public static void main(String[] args) {
        String str="abc123";
        System.out.println("分配一个容量为10个字节的缓存区");
        System.out.println("-------allocate(10)-------");
        ByteBuffer buffer = ByteBuffer.allocate(10);  //设置缓存区
        int capacity = buffer.capacity();
        int limit = buffer.limit();
        int position = buffer.position();
        System.out.println("capacity:"+capacity);
        System.out.println("limit:"+limit);
        System.out.println("position:"+ position);    //输出容量 边界 和位置
        System.out.println();

        System.out.println("向容器中增加数据");
        System.out.println("-------put()-------");
        buffer.put(str.getBytes());             //将str编码放入buffer缓存区中
        capacity = buffer.capacity();
        limit = buffer.limit();
        position = buffer.position();
        System.out.println("capacity:"+capacity);
        System.out.println("limit:"+limit);
        System.out.println("position:"+ position);//输出容量 边界 和位置
        System.out.println();

        System.out.println("切换模式,切换成读取模式");
        System.out.println("-------flip()-------");
        buffer.flip();                  //转换为读写模式,limit变为容器内总字节数
        capacity = buffer.capacity();
        limit = buffer.limit();
        position = buffer.position();
        System.out.println("capacity:"+capacity);
        System.out.println("limit:"+limit);
        System.out.println("position:"+ position);//输出容量 边界 和位置
        System.out.println();

        System.out.println("读取数据");
        System.out.println("-------get()-------");
        byte[] bytes = new byte[buffer.limit()];  //创建一个缓存区界限值大小的数组
        buffer.get(bytes);                  //读取这个数组
        String s = new String(bytes, 0, buffer.limit());//将读取到的东西解码
        System.out.println(s);
        capacity = buffer.capacity();
        limit = buffer.limit();
        position = buffer.position();
        System.out.println("capacity:"+capacity);
        System.out.println("limit:"+limit);
        System.out.println("position:"+ position);//输出容量 边界 和位置
        System.out.println();

        System.out.println("重复读取");
        System.out.println("-------rewind()-------");
        buffer.rewind();            //重置位置指针
        capacity = buffer.capacity();
        limit = buffer.limit();
        position = buffer.position();
        System.out.println("capacity:"+capacity);
        System.out.println("limit:"+limit);
        System.out.println("position:"+ position);//输出容量 边界 和位置
        System.out.println();

        System.out.println("清空缓冲区");
        System.out.println("--------clear()----------------");
        //-clear()并不是把缓冲区里面的字节数据清掉,而是把这些指针,设置到初始状态
        buffer.clear();
        capacity = buffer.capacity();
        limit = buffer.limit();
        position = buffer.position();
        System.out.println("capacity:"+capacity);
        System.out.println("limit:"+limit);
        System.out.println("position:"+ position);
        System.out.println();
        //检查一下这个缓存区的字节数据还在么
        byte[] bytes1 = new byte[buffer.limit()];
        buffer.get(bytes1);
        System.out.println(new String(bytes,0,6));


    }
}

在这里插入图片描述
在这里插入图片描述


import java.nio.ByteBuffer;

public class Test1 {
    public static void main(String[] args) {
        String str="123abc";
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put(str.getBytes());

        //读取模式
        buffer.flip();
        byte[] bytes = new byte[buffer.limit()];
        buffer.get(bytes,0,2);//写入两个字节
        System.out.println(buffer.position());

        buffer.mark();

        buffer.get(bytes,2,2);//在写入两个字节
        System.out.println(buffer.position());

        String s = new String(bytes, 0, 4);//解码
        System.out.println(s);
        buffer.reset();     //重置指针
        System.out.println(buffer.position());//打印指针位置

        if(buffer.hasRemaining()){          //查看是否还有字节未读取 如果有就打印剩下的字节数
            System.out.println(buffer.remaining());
        }
    }
}

在这里插入图片描述

  1. 缓冲区:非直接缓冲区,和直接缓冲区
    非直接缓冲区:将缓冲区建立在JVM的内存中
    直接缓冲区:将缓冲区建立在物理内存中

    非直接缓冲区allocate(1024)
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

    建立直接缓冲区allocateDirect(1024);
    ByteBuffer byteBuffer1 = ByteBuffer.allocateDirect(1024);在这里插入图片描述
    在这里插入图片描述

  2. 通道:Channel 类似于传统的“流”。只不过 Channel本身不能直接访问数据, Channel 只能与Buffer 进行交互。
    方式1: getChannel();获取通道
    方式2:通过FileChannel中的静态方法 open()可以打开一个通道
    方式3:JDK1.7之后提供了一个工具类 Files newByteChannel()

//用通道来复制文件
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test2 {
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("D:\\a.txt");
        FileOutputStream out = new FileOutputStream("C:\\a.txt");

        FileChannel inChannel = in.getChannel();
        FileChannel outChannel = out.getChannel();

        //分配一个非直接缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024 * 8);
        //读写文件
        while(inChannel.read(buffer)!=-1){
            //切换读取模式
            buffer.flip();
            //写数据
            outChannel.write(buffer);
            //清空缓冲区
            buffer.clear();
        }
    }
}

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Test3 {
    public static void main(String[] args) throws IOException {
        
        FileChannel inChannel = FileChannel.open(Paths.get("D:\\a.txt"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("C:\\a.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
        //StandardOpenOption.CREATE_NEW 文件不存在就创建,存在就报错
        //StandardOpenOption.CREATE 文件不存在,就创建,存在 就覆盖
        ByteBuffer buffer = ByteBuffer.allocate(1024 * 8);
        while(inChannel.read(buffer)!=-1){
            buffer.flip();
            outChannel.write(buffer);
            buffer.clear();
        }
        inChannel.close();
        outChannel.close();
    }
}
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


public class Test4 {
    public static void main(String[] args) throws IOException {
        FileChannel in = (FileChannel) Files.newByteChannel(Paths.get("D:\\a.txt"), StandardOpenOption.READ);
        FileChannel out = (FileChannel) Files.newByteChannel(Paths.get("C:\\a.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

    }
}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Test5 {
    public static void main(String[] args) throws IOException {
        //Files类的复制方法
        Files.copy(Paths.get("D:\\a.txt"),Paths.get("C:\\a.txt"), StandardCopyOption.REPLACE_EXISTING);
        Files.copy(new FileInputStream("D:\\a.txt"),Paths.get("C:\\a1.txt"),StandardCopyOption.REPLACE_EXISTING);
        Files.copy(Paths.get("D:\\a.txt"),new FileOutputStream("C:\\a2.txt"));


        //Files的剪切方法
        Files.move(Paths.get("D:\\a.txt"),Paths.get("a.txt"));
    }
}

  1. 通道之间的相互传输:通道之间的数据传输 用的也是直接缓冲区的方式
    transferFrom()
    transferTo()
public class MyTest{
 public static void main(String[] args) throws IOException {
        FileChannel in = FileChannel.open(Paths.get("E:\\MyTest.txt"), StandardOpenOption.READ);
      FileChannel out = FileChannel.open(Paths.get("D:\\MyTestCopy.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        //in.transferTo(0,in.size(),out);//把数据读到 输出通道中取 完成文件的复制
        //或者使用输出通道
        out.force(false);
        out.transferFrom(in,0,in.size()); //写出数据,写出的数据从输入通道中来
        in.close();
        out.close();
    }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值