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 holds 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 to a StringBuilder
        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.

Leave a Reply

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