How do I reread the content of a buffer?

The example shown below tells you how to reread the contents of a buffer. To reread the data from a buffer we can use the buffer’s rewind() method. This method set the position back to 0 while the limit is unchanged, it still hold the value of how many data can be read from the buffer.


import java.nio.CharBuffer;

public class BufferRewind {
    public static void main(String[] args) {
        CharBuffer buffer = CharBuffer.allocate(1024);
        buffer.put("The quick brown fox jumps over the lazy dog.");

        // Read buffer's data using the get() method call.
        while (buffer.hasRemaining()) {

        // Rewind the buffer will set the position back to 0.
        // We rewind the buffer so that we can reread the buffer
        // data for another purposes.

        // Reread the buffer and append its data the a StringBuilder
        // object.
        StringBuilder bufferText = new StringBuilder();
        while (buffer.hasRemaining()) {

The output of the code snippet:

The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.


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.