java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.nio;

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());
        }
    }
}