If you want to clear a buffer, but you want to keep the unread data in the buffer then you need to use the compact()
method of the buffer. The compact()
method will copy the unread data to the beginning of the buffer and set the position right after the unread data. The limit
itself still have the value equals to the buffer capacity. The buffer will be ready to be written again without overwriting the unread data.
package org.kodejava.io;
import java.nio.CharBuffer;
public class BufferCompact {
public static void main(String[] args) throws Exception {
CharBuffer buffer = CharBuffer.allocate(64);
buffer.put("Let's write some Java code! ");
System.out.println("Position: " + buffer.position());
System.out.println("Limit : " + buffer.limit());
// Read 10 chars from the buffer.
buffer.flip();
for (int i = 0; i < 10; i++) {
System.out.print(buffer.get());
}
System.out.println();
System.out.println("Position: " + buffer.position());
System.out.println("Limit : " + buffer.limit());
// clear the buffer using compact() method.
buffer.compact();
System.out.println("Position: " + buffer.position());
System.out.println("Limit : " + buffer.limit());
// Write and read some more data.
buffer.put("Add some more data.");
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print(buffer.get());
}
}
}
The output of the code snippet above is:
Position: 28
Limit : 64
Let's writ
Position: 10
Limit : 28
Position: 18
Limit : 64
e some Java code! Add some more data.
Latest posts by Wayan (see all)
- How do I use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025