由于JDK中提供的ByteBuffer无法动态扩容,并且API使用复杂等原因,Netty中提供了ByteBuf。
Bytebuf的API操作更加便捷,可以动态扩容,提供了多种ByteBuf的实现,以及高效的零拷贝机制。
ByteBuf的操作
ByteBuf有三个重要的属性:capacity容量,readerIndex读取位置,writerIndex写入位置
提供了readerIndex和weiterIndex两个变量指针来支持顺序读和写操作
下图显示了一个缓冲区是如何被两个指针分割成三个区域的:
代码示例:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.util.Arrays;
public class ByteBufDemo {
public static void main(String[] args) {
// 1.创建一个非池化的ByteBuf,大小为10个字节
ByteBuf buf = Unpooled.buffer(10);
System.out.println("原始ByteBuf为:" + buf.toString());
System.out.println("1.ByteBuf中的内容为:" + Arrays.toString(buf.array()) + "\n");
// 2.写入一段内容
byte[] bytes = {1, 2, 3, 4, 5};
buf.writeBytes(bytes);
System.out.println("写入的bytes为:" + Arrays.toString(bytes));
System.out.println("写入一段内容后ByteBuf为:" + buf.toString());
System.out.println("2.ByteBuf中的内容为:" + Arrays.toString(buf.array()) + "\n&#