1.介绍
ByteBuf是Netty的数据容器对象;
Unpooled是操作数据容器的工具类;
2.指针
进行readByte和writeByte方法的调用时会改变readIndex和writeIndex的值,而调用set和get方法时不会改变readIndex和writeIndex的值。上面的测试案例中打印的writeIndex和readIndex均为1,并未在调用set和get方法后被改变。
public static void main(String[] args) { ByteBuf heapBuf = Unpooled.buffer(5); heapBuf.writeByte(1); System.out.println("writeIndex : " + heapBuf.writerIndex()); //writeIndex : 1 heapBuf.readByte(); System.out.println("readIndex : " + heapBuf.readerIndex()); //readIndex : 1 heapBuf.setByte(2, 6); System.out.println("writeIndex : " + heapBuf.writerIndex()); //writeIndex : 1 heapBuf.getByte(2); System.out.println("readIndex : " + heapBuf.readerIndex()); //readIndex : 1 for (int i = 0; i < heapBuf.capacity(); i++) { System.out.println(heapBuf.getByte(i)); } }
效果
writeIndex : 1 readIndex : 1 writeIndex : 1 readIndex : 1 1 0 6 0 0 Disconnected from the target VM, address: '127.0.0.1:62437', transport: 'socket'
3.String转为ByteBuf
public static void main(String[] args) { ByteBuf buffer = Unpooled.copiedBuffer("hello,word!", Charset.forName("utf-8")); if (buffer.hasArray()) { byte[] array = buffer.array(); System.out.println(new String(array, Charset.forName("utf-8"))); System.out.println("byteBuf=" + buffer); System.out.println(buffer.arrayOffset()); System.out.println(buffer.readerIndex()); System.out.println(buffer.writerIndex()); System.out.println(buffer.capacity()); int len = buffer.readableBytes(); //可读的字节数 System.out.println("len=" + len); for (int i = 0; i < len; i++) { System.out.println((char) buffer.getByte(i)); } System.out.println(buffer.getCharSequence(0, 4, Charset.forName("utf-8"))); System.out.println(buffer.getCharSequence(4, 1, Charset.forName("utf-8"))); } }
效果
hello,word! byteBuf=UnpooledUnsafeHeapByteBuf(ridx: 0, widx: 11, cap: 33) 0 0 11 33 len=11 h e l l o , w o r d ! hell o Process finished with exit code 0