How do I clear a buffer using clear method?

The code below show you how to clear a buffer using the clear() method call. The clear method call set the position in the buffer to 0 and limit to the capacity of the buffer.

We usually call the clear() method after we read the entire content of a buffer and clear it for ready to be written again. The clear() method is actually not clearing the data in the buffer. It only clear the marker where you can write the data in the buffer and the unread data will be forgotten.

package org.kodejava.example.nio;

import java.nio.LongBuffer;

public class BufferClear {
    public static void main(String[] args) {
        //
        // Allocates a new LongBuffer.
        //
        LongBuffer buffer = LongBuffer.allocate(64);

        //
        // Write the long array into the buffer.
        //
        buffer.put(new long[] {10, 20, 30, 40, 50, 60, 70, 80});
        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());
        
        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.println(buffer.get());
        }

        //
        // clear() method set the position to zero and limit
        // to the capacity of the buffer.
        //
        buffer.clear();
        System.out.println("Position: " + buffer.position());
        System.out.println("Limit   : " + buffer.limit());
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply