IoBuffer和ByteBuffer

来源:互联网 发布:什么是多媒体数据库 编辑:程序博客网 时间:2024/04/30 04:20
MINA does not use NIO ByteBuffer directly for two reasons

ByteBuffer继承了Buffer

Buffer中有4个重要的Attributes:
        

        Capacity: the capacity is set when the buffer is created and can never be changed开的内存的大小,一旦设定了,就不能更改了。注意,这里指的是原生的NIO

        Limit: the first element of the buffer that should not be read or written。可以分读写来统计。在写入buffer时,limit表示有多少空间可以写入。在从buffer写出时,limit表示有多少可以写出。

        Position: the index of the next element to be read or written。下一个要被读或写的位置。

        Mark: a remembered position. Calling mark() set mark=position。标记位,可以记住某个position,方便后续操作。

        他们的关系如下:

0<=mark<=position<=limit<=capacity。


   

对于ByteBuffer有如下常用的操作:

flip()::读写模式的转换。

rewind() :将 position 重置为 0 ,一般用于重复读。

clear() :清空 buffer ,准备再次被写入 (position 变成 0 , limit 变成 capacity) 。

compact(): 将未读取的数据拷贝到 buffer 的头部位。

mark() 、 reset():mark 可以标记一个位置, reset 可以重置到该位置。



get()getShort()等一系列get操作:获取ByteBuffer中的内容,当然这里get的内容都是从position开始的,所以要时刻注意position。每次get之后position都会改变。Position的变化是根据你get的类型,如果是short,那就是2byte,如果是int,那就是增加4byte,即32


put()putShort()等一系列put操作:向ByteBuffer添加内容,这里put的内容都是从position开始的。每次put之后position都会改变。


Buffers are not thread-safe. If you want to access a given buffer concurrently from multiple threads, you will need to do your own synchronization prior to accessing the buffer.


Two Reasons

 It doesn't provide useful getters and putters such as fill, get/putString, and get/putAsciiInt() enough.

 It is difficult to write variable-length data due to its fixed capacity

第二点,IoBuffer实现了Auto ExpandAuto Shrink。这就意味了,capacity可以根据传输内容的大小自动变更了。在使用上,我们可以这样写:


IoBuffer buf = IoBuffer.allocate(1024).setAutoExpand(true);


0 0
原创粉丝点击