读数据
读取数据的小案例:
package com.nio;
import java.nio.ByteBuffer;
/**
* 一、缓存区(Buffer):在java NIO 中负责数据点额存取。缓存区就是数组。用于存储不同数据类型的数据
*
* 根据数据类型不同(boolean除外),提供了相应类型的缓存区:
* ByteBuufer
* CharBuffer
* ShortBuffer
* IntBuffer
* LongBuffer
* FloatBuffer
* DoubleBuffer
*
* 上述缓存区的管理方式几乎是一致的,都是通过allocate()方法获取缓存区的
*
* 二、缓存区数据存取的两个方法 (缓存区的底层说白了就是数组)
* put():存入数据到缓存区中
* get(): 获取缓存区中的数据
*
* 三、缓存区中的四个核心属性
* private int mark = -1;//标记,表示记录当前position的位置。可以通过reset()恢复到mark的位置
* private int position = 0;//位置,表示缓存区中正在操作数据的位置
* private int limit;//界限,表示缓存区中可以操作数据的大小,(limit后数据不能进行读写)
* private int capacity; //容量,表示缓存区中最大存储数据的容量,一旦声明不能改变
* position<=limit<=capacity
*/
public class TestBuffer {
public static void main(String[] args) {
String str="abcde";
//1.分配一个指定大小的缓存区
ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println("-------------allocate()---------------");
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
//2.利用put() 存入数据到缓存区中
buffer.put(str.getBytes());
System.out.println("-------------put()---------------");
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
//3.切换到读取数据的模式
buffer.flip();
System.out.println("-------------flip()---------------");
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
//4.利用get()读取缓存区中的数据
byte[] dst = new byte[buffer.limit()];
buffer.get(dst);
System.out.println(new String(dst,0,dst.length));
System.out.println("-------------get()---------------");
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
//5.rewind():可重复读取数据
buffer.rewind();
System.out.println("-------------rewind()---------------");
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
//6.clear():清空缓存区,但是缓存区中的数据依然存在,但是出于一种“被遗忘”状态
buffer.clear();
System.out.println("-------------clear()---------------");
System.out.println(buffer.position());
System.out.println(buffer.limit());
System.out.println(buffer.capacity());
System.out.println((char) buffer.get());
}
}
运行结果: -------------allocate()--------------- 0 1024 1024 -------------put()--------------- 5 1024 1024 -------------flip()--------------- 0 5 1024 abcde -------------get()--------------- 5 5 1024 -------------rewind()--------------- 0 5 1024 -------------clear()--------------- 0 1024 1024 A
浙公网安备 33010602011771号