netty学习笔记05——buffer的使用
一个简单的demo
public class BasicBuffer {
public static void main(String[] args) {
//创建一个buffer,大小为5,即可以存放5个int
IntBuffer intBuffer = IntBuffer.allocate(5);
//向buffer中存放数据
intBuffer.put(10);
intBuffer.put(11);
intBuffer.put(12);
intBuffer.put(13);
intBuffer.put(14);
//如何从buffer取数据
//将buffer转换,读写切换
intBuffer.flip();
while(intBuffer.hasRemaining()){
System.out.println(intBuffer.get());
}
}
}
可以看出buffer的api包括以下几部分:
- IntBuffer.allocate(),给buffer分配大小,当往buffer里放置的元素数量超过allocate分配的数量的时候,将会报错java.nio.BufferOverflowException
Exception in thread "main" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:521)
at java.nio.HeapIntBuffer.put(HeapIntBuffer.java:169)
at com.cqupt.sirius.nettyAction.nioapi.BasicBuffer.main(BasicBuffer.java:16)
- put(),就是放置元素的api
- flip(),读写模式切换。
- hasRamaining(),get(),在读写模型下分别有不同的效果:在写模式下,hasRamaining()是指示还有多少空间可以写,get()是指向下一个未写的空间;在读模式下,hasRemaining是指示还有多少内容可以读,get()是指向下一个未读的内容