NIO 是什么
java.nio全称java non-blocking(非阻塞) IO(实际上是 new io),是指jdk1.4 及以上版本里提供的新api(New IO) ,为所有的原始类型(boolean类型除外)提供缓存支持的数据容器,使用它可以提供非阻塞式的高伸缩性网络。
NIO与IO的区别
| IO | NIO |
|---|---|
| 面向流(Stream Oriented) | 面向缓冲区(Buffer Oriented) |
| 阻塞IO(Blocking IO) | 非阻塞(Non Blocking IO) |
| 无 | 选择器(Selectors) |
NIO系统的核心是:通道(Channel)和缓冲区(Buffer)
缓冲区(Buffer)
位于 java.nio 包,所有缓冲区都是 Buffer 抽象类的子类,使用数组对数据进行缓冲。
除了 boolean 类型,Buffer 对每种基本数据类型都有针对的实现类:
- ByteBuffer
- CharBuffer
- ShortBuffer
- IntBuffer
- LongBuffer
- FloatBuffer
- DoubleBuffer
创建缓冲区通过 xxxBuffer.allocate(int capacity)方法
ByteBuffer buf1 = ByteBuffer.allocate(512); LongBuffer buf2 = LongBuffer.allocate(1024); ……缓冲区的属性
容量(capacity):表示缓冲区存储数据的最大容量,不能为负数,创建后不可修改。
限制:第一个不可以读取或写入的数据的索引,即位于 limit 后的数据不能读写。不能为负数,不能大于容量。
位置(position):下一个要读取或写入的数据的索引,位置不能为负数,不能大于 limit
标记(mark):标记是一个索引,通过 Buffer 中的 mark() 方法指 Buffer 中一个特定的 position,之后可以通过 reset() 方法回到这个 postion。
Buffer 的常用方法
| 方法名称 | 说明 |
|---|---|
| Buffer clear() | 清空缓冲区并返回对缓冲区的引用 |
| Buffer flip() | 将缓冲区的 limit 设置为当前位置,并将当前位置重置为0 |
| int capacity() | 返回 Buffer 的容量大小 |
| boolean hasRemaining() | 判断缓冲区是否还有元素 |
| int limit() | 返回 限制的位置 |
| Buffer limit(int n) | 将设置缓冲区界限为 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() 方法和 put() 方法
缓冲区存取数据操作
package testnio; import java.nio.ByteBuffer; public class TestBuffer1 { public static void main(String[] args) { testuse(); } public static void testuse() { //1.分配一个指定大小的缓冲区 ByteBuffer buf=ByteBuffer.allocate(1024); System.out.println("---------------allocate()----------------"); System.out.println(buf.position()); System.out.println(buf.limit()); System.out.println(buf.capacity()); //2.利用 put() 存入数据到缓冲区中 String str="hello";
