CharBuffer Wrap Flip And Compact

Fill a CharBuffer with put, flip to drain with get, and compact to keep unread chars for the next write instead of clearing them away.

JavaData Integrity

Code

snippet
import java.nio.CharBuffer;
import java.nio.ReadOnlyBufferException;

public class TextBufferLifecycle {

    public static void main(String[] args) {
        CharBuffer buf = CharBuffer.allocate(16);
        buf.put("audit-2026"); // 相对 put:position 前进到 10
        System.out.println("write mode: position=" + buf.position() + " limit=" + buf.limit());

        // flip:limit=position、position=0,从写入模式切到读出模式
        buf.flip();
        char[] head = new char[5];
        buf.get(head); // 相对 get:只取前 5 个字符
        System.out.println("drained: " + new String(head));
        System.out.println("after get: position=" + buf.position() + " remaining=" + buf.remaining());

        // compact:把未读的 "-2026" 挪到开头,接着写而不是丢掉
        buf.compact();
        buf.put('!'); // 续写
        buf.flip();   // 再切回读出模式
        System.out.println("remaining text: " + buf);

        // wrap(CharSequence) 得到的是只读缓冲:写入直接抛 ReadOnlyBufferException
        CharBuffer shared = CharBuffer.wrap("immutable");
        try {
            shared.put('x');
        } catch (ReadOnlyBufferException e) {
            System.out.println("wrap(CharSequence) refuses writes");
        }
    }
}

How it works

The code’s whole job belongs to the class TextBufferLifecycle and the function main.

Watch out for

  • Every symbol it uses is a language built-in — nothing needs fetching.

Using it

Signature: public static void main(String[] args)

Output lines are prefixed (write mode: position=, drained:, after get: position=), so each step’s effect shows up clearly in the output.

The key statements, annotated

CharBuffer shared = CharBuffer.wrap("immutable");
buf.put("audit-2026"); // 相对 put:position 前进到 10
System.out.println("write mode: position=" + buf.position() + " limit=" + buf.limit());
CharBuffer buf = CharBuffer.allocate(16);

Interactive Tools for This Topic

FAQ

What does CharBuffer Wrap Flip And Compact print when run?
No setup needed: run the file and look for labeled lines like `write mode: position=`, `drained:`, `after get: position=` in the output.