一、ByteBuffer 结构
ByteBuffer 有以下重要属性
-
capacity
-
position
-
limit
一开始
写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态
flip 动作发生后,position 切换为读取位置,limit 切换为读取限制
读取 4 个字节后,状态
clear 动作发生后,状态
compact 方法,是把未读完的部分向前压缩,然后切换至写模式
二、字符串与 ByteBuffer 互转
public static void main(String[] args) {
//字符串存入ByteBuffer
//1 put bytes []
ByteBuffer buffer1=ByteBuffer.allocate(16);
buffer1.put("ni hao ma".getBytes());
debugAll(buffer1);
//2 Charset
ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("你好吗");
debugAll(buffer2);
//3 wrap
ByteBuffer buffer3 = ByteBuffer.wrap("ni hao ma".getBytes());
debugAll(buffer2);
// ByteBufffer 读取到字符串里
System.out.println(StandardCharsets.UTF_8.decode(buffer3).toString());
}
控制台输出: