在Netty中,还有另外一个比较常见的对象ByteBuf,它其实等同于Java Nio中的ByteBuffer,但是ByteBuf对Nio中的ByteBuffer的功能做了很多增强,下面介绍一下ByteBuf。
下面这段代码演示了ByteBuf的创建以及内容的打印,这里显示出了和普通ByteBuffer最大的区别之一,就是ByteBuf可以自动扩容,默认长度是256,如果内容长度超过阈值时,会自动触发扩容
public class ByteBufExample {
public static void main(String[] args) {
ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(); //可自动扩容
log(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 128; i++) {
sb.append(" - " + i);
}
buffer.writeBytes(sb.toString().getBytes());
log(buffer);
}
private static void log(ByteBuf buf) {
StringBuilder builder = new StringBuilder()
.append(" read index:").append(buf.readerIndex())//获取读索引
.append(" write index:").append(buf.writerIndex()) //获取写索引
.append(" capacity:").append(buf.capacity())//获取容量
.append(StringUtil.NEWLINE);
//把ByteBuf中的内容,dump到StringBuilder中
ByteBufUtil.appendPrettyHexDump(builder, buf);
System.out.println(builder.toString());
}
}
参考:https://www.cnblogs.com/snail-gao/p/15595747.html
标签:ByteBuffer,buffer,StringBuilder,详解,ByteBuf,buf,append From: https://www.cnblogs.com/weidaijie/p/16827327.html