Mina学习之IoBuffer

IoBuffer是一个被MINA体系所使用的字节数组。它是ByteBuffer的替代品,Mina不使用NIO的ByteBuffer有两个原因:

1. ByteBuffer没有提供更多有用的api,如fill,get/putString等

2. ByteBuffer是定长的,故无法写入变长的数据

IoBuffer的操作

分配新的Buffer

IoBuffer是一个抽象类,不能直接实例化,想分配IoBuffer,我们需要用以下两种方法中的一个:

// Allocates a new buffer with a specific size, defining its type (direct or heap)
public static IoBuffer allocate(int capacity, boolean direct)

// Allocates a new buffer with a specific size
public static IoBuffer allocate(int capacity)

其中,参数capacity表示该IoBuffer的容量,参数direct标识buffer的类型,true表示直接缓冲区,false表示堆缓冲区。

创建可自动扩展长度的Buffer

NIO API中想创建可扩展长度的缓冲区很不容易,因为buffer长度是固定的。IoBuffer引入了一个自动扩展的属性,该属性能够实现自动扩展缓冲区的长度。
当长度不够时,会自动将缓冲区的大小增加到2倍。
IoBuffer buffer = IoBuffer.allocate(8);
buffer.setAutoExpand(true);
buffer.putString("12345678", encoder);
// Add more to this buffer
buffer.put((byte)10);

创建可自动缩小长度的Buffer

同样,IoBuffer也提供了一个方法来释放多余的空间,如果autoShrink被打开后,调用compact()后只有1/4或者更少的空间被占用,IoBuffer则会缩小至一半的容量。

IoBuffer buffer = IoBuffer.allocate(16);
buffer.setAutoShrink(true);
buffer.put((byte)1);
System.out.println("Initial Buffer capacity = "+buffer.capacity());
buffer.shrink();
System.out.println("Initial Buffer capacity after shrink = "+buffer.capacity());
buffer.capacity(32);
System.out.println("Buffer capacity after incrementing capacity to 32 = "+buffer.capacity());
buffer.shrink();
System.out.println("Buffer capacity after shrink= "+buffer.capacity());
结果如下:
Initial Buffer capacity = 16
Initial Buffer capacity after shrink = 16
Buffer capacity after incrementing capacity to 32 = 32
Buffer capacity after shrink= 16




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值