创建ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(10);
ByteBuffer buffer01 = Charset.defaultCharset().encode("hello world");
ByteBuffer buffer02 = ByteBuffer.wrap("hello".getBytes());
ByteBuffer buffer03 = StandardCharsets.UTF_8.encode("hehe");
CharBuffer decode = StandardCharsets.UTF_8.decode(buffer02);
ByteBuffer结构
- position : 读取或者写入的指针位置
- limit : 读取或者写入限制位置
- capacity : 容量
常用方法
- put() :往buffer里面添加数据,,, 也可以通过channel读
- get() : 会获取一个字节的数据,,指针往后走
- get(i) : 获取指定位置的数据,,指针不会动
- flip() : 切换到读模式,,,, position变为0 ,,limit变为数据长度
- clear() : 切换到写模式 ,, position变成0,,limit变成 capacity
- compact() : 压缩,有的时候数据读了一部分,没读完,又需要写入新的数据,compact将position变成剩余数据的长度,limit变成capacity
- mark() 和 reset(): 有的部分需要反复的读,,用mark()设置一个标记, reset()回滚到那个标记
- hasRemaining() : 是否有剩余字节可读写
- rewind() : 将position变为0