← 中文资源

简体中文版本

ByteBuffer 用 flip 与 slice 切出共享子视图

演示写完 ByteBuffer 后 flip 切换为读模式,再用 slice() 和 slice(index, length) 切出共享底层字节但拥有独立游标的子视图,就地改写且不扰动父位置。

阅读英文原文

实现说明

ByteBuffer 用 flip 与 slice 切出共享子视图以类 FrameSubViews和函数 main为骨架。

使用要点

  • 依靠语言原生工具链内置能力就能跑通——不用追加下载。
  • 跑完文件,输出里会留下标记——status=、payload=、updated header=。

常见问题

运行「ByteBuffer 用 flip 与 slice 切出共享子视图」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 status=、payload=、updated header= 标签标明各步骤。

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

核心语句

headerSlice.putInt(0, 404); // writes through to the shared backing bytes
System.out.println("updated header=" + frame.getInt(0) + " parent pos=" + frame.position());
int status = frame.getInt(); // advances parent position to 4
// slice() creates a view of remaining bytes [4..8) starting at position 0
ByteBuffer payloadView = frame.slice();
frame.put("BODY".getBytes(StandardCharsets.UTF_8));

代码示例

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

public class FrameSubViews {

    public static void main(String[] args) {
        ByteBuffer frame = ByteBuffer.allocate(12);
        frame.putInt(200); // 4-byte status header
        frame.put("BODY".getBytes(StandardCharsets.UTF_8));
        frame.flip(); // position=0, limit=8

        int status = frame.getInt(); // advances parent position to 4
        // slice() creates a view of remaining bytes [4..8) starting at position 0
        ByteBuffer payloadView = frame.slice();
        System.out.println("status=" + status
                + " slice pos=" + payloadView.position()
                + " cap=" + payloadView.capacity());

        byte[] bytes = new byte[payloadView.remaining()];
        payloadView.get(bytes);
        System.out.println("payload=" + new String(bytes, StandardCharsets.UTF_8));

        // slice(index, length) creates a fixed window without moving parent position
        ByteBuffer headerSlice = frame.slice(0, 4);
        headerSlice.putInt(0, 404); // writes through to the shared backing bytes
        System.out.println("updated header=" + frame.getInt(0) + " parent pos=" + frame.position());
    }
}