ByteBuffer 内部结构 以及正确使用姿势介绍

356 阅读1分钟

ByteBuffer 正确使用流程

  1. 向buffer 写入数据,例如调用 channle.read(buffer)
  2. 调用 flip() 切换至读模式。
  3. 从 buffer 读取数据,例如调用 buffer.get
  4. 调用 clear() 或 compact() 切换至写模式。
  5. 重复 1-4

初次体验示例

public class TestByteBuffer {

    public static void main(String[] args) {
//        获取 FileChannel
        String  s = (String) System.getProperties().get("user.dir");
        try (FileChannel channel = new FileInputStream(s + "\a.txt").getChannel()) {
            // 分配一个新的字节缓冲区。 划分一块内存作为缓冲区。划分的大小 有 allocate 参数决定
            ByteBuffer byteBuffer = ByteBuffer.allocate(10);
            // 从信道里读取数据  向缓冲区写入
            channel.read(byteBuffer);
            // byteBuffer 现在有内容了   flip 切换到 buffer 的读模式
             byteBuffer.flip();
            // 是否还有剩余的未读的数据
             while(byteBuffer.hasRemaining()) {
                 char c = (char) byteBuffer.get();
                 System.out.println(c);
             }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ByteBuffer 结构

重要属性
  • capacity
  • position
  • limit
内部结构图示
ByteBuffer 刚被创建出来

image.png

写模式下

position 代表当前写入指针,limit 指向capacity 写入限制。 image.png

flip 动作发生,position 切换为读取位置,limit 转为读取限制。

image.png

读取完成

image.png

读取完成 clear 切换为写模式。

与刚被创建出来相同 hh

没有读完,使用 compact 方法,把未读完的部分向前压缩 切换至写模式

写模式 limit 总是在容量大小位置。 而 compact 模式下 positon 新位置变为 limit - positon image.png

优秀博客集锦

玩转ByteBuffer
一文搞懂ByteBuffer