How do I clear a buffer using compact method?

If you want to clear a buffer but you want to keep the unread data in the buffer then you need to use the compact() method of the buffer. The compact() method will copy the unread data to the beginning of the buffer and set the position right after the unread data. The limit itself still have the value equals to the buffer capacity. The buffer will be ready to be written again without overwrite the unread data.

package org.kodejava.example.io;

import java.nio.CharBuffer;

public class BufferCompact {
    public static void main(String[] args) throws Exception {
        CharBuffer buffer = CharBuffer.allocate(64);
        buffer.put("Let's write some Java code! ");

        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // Read 10 chars from the buffer.
        buffer.flip();
        for (int i = 0; i < 10; i++) {
            System.out.print(buffer.get());
        }
        System.out.println("");

        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // clear the buffer using compact() method.
        buffer.compact();
        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());

        // Write and read some more data.
        buffer.put("Add some more data.");

        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.print(buffer.get());
        }
    }
}

The output of the code snippet above is:

Position: 28
Limit   : 64
Let's writ
Position: 10
Limit   : 28
Position: 18
Limit   : 64
e some Java code! Add some more data.

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.