← 中文资源

简体中文版本

ByteBuffer 的 duplicate 与只读视图隔离

用 duplicate() 为读取方创建共享底层字节的独立游标,并用 asReadOnlyBuffer() 提供不可写且隐藏底层数组的只读视图以守住边界。

阅读英文原文

实现说明

ByteBuffer 的 duplicate 与只读视图隔离以类 BufferViewBoundaries和函数 main为骨架。

使用要点

  • 只借助默认工具链内置特性就足以跑通——不必额外补充安装。
  • 跑完文件,输出里会留下标记——cursor pos=、isReadOnly=、readOnly sees:。

常见问题

运行「ByteBuffer 的 duplicate 与只读视图隔离」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 cursor pos=、isReadOnly=、readOnly sees: 标签标明各步骤。

主要签名是 public static void main(String[] args)

核心语句

ByteBuffer mutable = ByteBuffer.wrap("TOKEN-42".getBytes(StandardCharsets.US_ASCII));
ByteBuffer readOnly = mutable.asReadOnlyBuffer();
byte[] seen = new byte[readOnly.remaining()];

代码示例

import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.charset.StandardCharsets;

public class BufferViewBoundaries {

    public static void main(String[] args) {
        ByteBuffer mutable = ByteBuffer.wrap("TOKEN-42".getBytes(StandardCharsets.US_ASCII));

        // duplicate() creates an independent cursor sharing the same backing bytes
        ByteBuffer cursor = mutable.duplicate();
        cursor.position(6);
        System.out.println("cursor pos=" + cursor.position() + " mutable pos=" + mutable.position());

        // asReadOnlyBuffer() prevents writes and hides the backing array (hasArray() is false)
        ByteBuffer readOnly = mutable.asReadOnlyBuffer();
        System.out.println("isReadOnly=" + readOnly.isReadOnly() + " hasArray=" + readOnly.hasArray());

        // Mutations on the original buffer remain visible through the shared read-only view
        mutable.put(6, (byte) '9');
        byte[] seen = new byte[readOnly.remaining()];
        readOnly.get(seen);
        System.out.println("readOnly sees: " + new String(seen, StandardCharsets.US_ASCII));

        try {
            readOnly.put(0, (byte) 'X');
        } catch (ReadOnlyBufferException ex) {
            System.out.println("write blocked: " + ex.getClass().getSimpleName());
        }
    }
}