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 is only clear the marker where you can write the data in the buffer and the unread data will be forgotten.

package org.kodejava.io;

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

The output of the code snippet:

Position: 8
Limit   : 64
10
20
30
40
50
60
70
80
Position: 0
Limit   : 64
Wayan

Leave a Reply

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