Java NIO指的是new IO ,相对OIO,也称non-blocking IO,对应四种基本IO类型中的IO多路复用,主要有有三大核心组件,Channel(管道),Buffer(缓冲区),selector(选择器)
基本操作如下注释:
package com.example.demo; import java.nio.IntBuffer; /** * Created by Administrator on 2019/9/22. */ public class NioTest { static IntBuffer intBuffer=null; public static void main(String[] args) { intBuffer=IntBuffer.allocate(20);//默认为写入模式 print();//创建缓冲区p:l:c 0:20:20 p为position l为limit c为capacity put();//插入5个数 print();//p:l:c 5:20:20 写入模式下写入数据只是改变postition的值 get(2);//输出两个0 print();//p:l:c 7:20:20 没有切换模式的情况下,get也变为在末尾添加两个0 flip();//p:l:c 0:7:20 翻转,切换为读取模式 get(4); print();//p:l:c 4:7:20 get(2); print();//p:l:c 6:7:20 clear();//p:l:c 0:20:20 切回写入模式,并清空 // compact();//p:l:c 1:20:20 切回写入模式,保留未读取的数据 print(); } public static void put(){ for (int i = 0; i < 5; i++) { intBuffer.put(i); } System.out.println("putting data"); } public static void print(){ System.out.println("position=="+intBuffer.position()); System.out.println("limit=="+intBuffer.limit()); System.out.println("capacity=="+intBuffer.capacity()); } public static void flip(){ intBuffer.flip(); System.out.println("flipping"); } public static void clear(){ intBuffer.clear(); System.out.println("clearing the buffer"); } public static void compact(){ intBuffer.compact(); System.out.println("compacting the buffer"); } public static void get(int n){ System.out.println("starting to read"); for (int i = 0; i < n; i++) { System.out.println("read data=="+intBuffer.get()); } System.out.println("ending to read"); } }
输出
position==0
limit==20
capacity==20
putting data
position==5
limit==20
capacity==20
starting to read
read data==0
read data==0
ending to read
position==7
limit==20
capacity==20
flipping
starting to read
read data==0
read data==1
read data==2
read data==3
ending to read
position==4
limit==7
capacity==20
starting to read
read data==4
read data==0
ending to read
position==6
limit==7
capacity==20
clearing the buffer
position==0
limit==20
capacity==20