说明
1.Netty提供一个专门用来操作缓冲区(即Netty的数据容器)的工具类
2.常用方法
Unpooled获取Netty的数据容器ByteBuf
三个重要属性如下图
举例一
public class NettyByteBuf01 {public static void main(String[] args) {//创建一个ByteBuf/*1.创建对象,该对象会包含一个数组,byte[10]2.在Netty的buffer中,不需要使用flip进行读写反转底层维护了readerIndex(记录下一个读) 和 writerIndex(记录下一个写)将buffer分成三个区域 :0 -> readerIndex--已经读取的区域readerIndex -> writerIndex --可读区域writerIndex -> capacity(数组大小) -->可写区域*/ByteBuf buffer = Unpooled.buffer(10);for (int i = 0; i < 10; i++) {buffer.writeByte(i); //writerIndex递增}System.out.println("容量大小为"+buffer.capacity());for (int i = 0; i < buffer.capacity(); i++) {System.out.println(buffer.getByte(i));}for (int i = 0; i < buffer.capacity(); i++) {System.out.println(buffer.readByte()); //readerIndex递增}}}
举例二
public class NettyByteBuf02 {public static void main(String[] args) {//创建ByteBufByteBuf buf = Unpooled.copiedBuffer("HelloWorld嘿嘿", StandardCharsets.UTF_8);//使用相关的APIif (buf.hasArray()) { //是否分配数组byte[] content = buf.array();System.out.println(new String(content, StandardCharsets.UTF_8));System.out.println("byteBuf=" + buf); //真实类型为一个内部类//byteBuf=UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf(ridx: 0, widx: 16, cap: 36)System.out.println(buf.arrayOffset()); // 偏移量System.out.println(buf.readerIndex());System.out.println(buf.writerIndex());System.out.println(buf.capacity()); //容量int len = buf.readableBytes();//可读的字节数System.out.println(len);//使用for循环取出for (int i = 0; i < len; i++) {System.out.print((char) buf.getByte(i));}System.out.println(buf.getCharSequence(0,4,StandardCharsets.UTF_8));//读取某一段,从index读len长度}}}
