ByteBuffer类学习


创建ByteBuffer:

ByteBuffer不能直接被new出来,需要使用allocate方法创建。

这样写会报错: ByteBuffer bfTest = new ByteBuffer();

正确写法: ByteBuffer bf = ByteBuffer.allocate(48);创建一个能够容纳48个字节的字节数组。



从ByteBuffer读数据:

使用getChar(5)并不改变当前position,而直接使用getChar会改变position。

请看测试代码和输出:


bf.getChar(5);

logger.debug(String.format("getchar(5) five times ====== capacity : %d , position : %d , limit : %d ", bf.capacity(),bf.position(),bf.limit()));

bf.getChar();

bf.getChar();

bf.getChar();

bf.getChar();

bf.getChar();

logger.debug(String.format("getchar() five times ====== capacity : %d , position : %d , limit : %d ", bf.capacity(),bf.position(),bf.limit()));


06:32:07.392 [main] DEBUG org.liujingyu.buffer_test.BufferTest - flip ====== capacity : 48 , position : 0 , limit : 14 

06:32:07.393 [main] DEBUG org.liujingyu.buffer_test.BufferTest - getchar(5) five times ====== capacity : 48 , position : 0 , limit : 14 

06:32:07.393 [main] DEBUG org.liujingyu.buffer_test.BufferTest - getchar() five times ====== capacity : 48 , position : 10 , limit : 14 

调用flip之后,postion归零,调用getChar(5)后,postion仍然是0。


测试代码请从github下载: https://github.com/mfcliu/netty-learning




参考资料:

http://ifeve.com/buffers/


你可能感兴趣的:(java,nio,ByteBuffer)