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.
package org.kodejava.io;
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.");
buffer.flip();
// Read buffer's data using the get() method call.
while (buffer.hasRemaining()) {
System.out.print(buffer.get());
}
System.out.println();
// 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.
buffer.rewind();
// Reread the buffer and append its data to a StringBuilder
StringBuilder bufferText = new StringBuilder();
while (buffer.hasRemaining()) {
bufferText.append(buffer.get());
}
System.out.println(bufferText);
}
}
The output of the code snippet:
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
Latest posts by Wayan (see all)
- How do I iterate through date range in Java? - October 5, 2023
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023