ByteBuffer Slice And Flip Sub-Views
Flip a ByteBuffer after writing and carve independent sub-views with slice() and slice(index, length) that share bytes without moving parent positions.
Code
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());
}
}Execution breakdown — ByteBuffer Slice And Flip Sub-Views
Everything happens inside the class FrameSubViews and the function main.
Points of care
- Executes straight out of the box using capabilities already in the core toolchain.
Putting it to use
Primary callable prototype reads public static void main(String[] args)
The file’s steps show up in the output as status=, payload=, updated header=.
Core lines
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));
Interactive Tools for This Topic
FAQ
- What does ByteBuffer Slice And Flip Sub-Views print when run?
- Running the file directly is enough — expect labeled output lines such as `status=`, `payload=`, `updated header=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.