ByteBuffer Flip And Compact
Move a ByteBuffer between write and read mode with flip, drain with get, and preserve unread bytes with compact instead of reallocating.
Code
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class BufferStaging {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(16);
System.out.println("new : pos=" + buffer.position() + " limit=" + buffer.limit());
buffer.put("ping".getBytes(StandardCharsets.UTF_8)); // 写模式推进 position
System.out.println("after put : pos=" + buffer.position());
buffer.flip(); // 写切读:limit 对齐已写位置,position 归零
System.out.println("after flip : pos=" + buffer.position() + " limit=" + buffer.limit());
byte[] received = new byte[buffer.remaining()];
buffer.get(received);
System.out.println("read : " + new String(received, StandardCharsets.UTF_8));
buffer.compact(); // 未读字节挪到开头,切回写模式,零重新分配
System.out.println("after compact: pos=" + buffer.position() + " limit=" + buffer.limit());
buffer.put("pong".getBytes(StandardCharsets.UTF_8));
buffer.flip();
byte[] next = new byte[buffer.remaining()];
buffer.get(next);
System.out.println("read : " + new String(next, StandardCharsets.UTF_8));
}
}How the snippet works
Count the class BufferStaging and the function main as the entire surface area of ByteBuffer Flip And Compact.
Applying it
Output lines are prefixed (new : pos=, after put : pos=, after flip : pos=), so reading the output means reading the steps in order.
Statements that matter
buffer.put("ping".getBytes(StandardCharsets.UTF_8)); // 写模式推进 position
System.out.println("after put : pos=" + buffer.position());
buffer.put("pong".getBytes(StandardCharsets.UTF_8));
byte[] received = new byte[buffer.remaining()];
Interactive Tools for This Topic
FAQ
- What does ByteBuffer Flip And Compact print when run?
- Running the file directly is enough — expect labeled output lines such as `new : pos=`, `after put : pos=`, `after flip : pos=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.