The Buffer
class is an abstract class in the java.nio
package, serving as the foundation for all buffer classes like ByteBuffer
, CharBuffer
, IntBuffer
, etc. A buffer is a container for a fixed amount of data of a specific primitive type.
Commonly Used Methods

Simple Program using ByteBuffer
This program demonstrates basic usage of a buffer to store and retrieve bytes.
import java.nio.ByteBuffer; public class SimpleBufferExample { public static void main(String[] args) { ByteBuffer buffer = ByteBuffer.allocate(10); // Capacity = 10 // Writing data to buffer for (int i = 0; i < 5; i++) { buffer.put((byte) (i + 65)); // storing ASCII A, B, C, D, E } buffer.flip(); // Switch from write mode to read mode // Reading data from buffer while (buffer.hasRemaining()) { byte b = buffer.get(); System.out.println("Read: " + (char) b); } } }
Problem Statement:
LotusJavaPrince is building a lightweight logging framework. Mahesh suggests using CharBuffer
to temporarily store log messages in memory before writing to a file. Write a Java program that stores log messages in a CharBuffer
, marks specific positions (for rollback), and rewinds or resets if needed before writing to a file.
import java.io.FileWriter; import java.io.IOException; import java.nio.CharBuffer; public class LogBufferSystem { public static void main(String[] args) { CharBuffer logBuffer = CharBuffer.allocate(100); // buffer with capacity of 100 chars // Step 1: Write initial log messages logBuffer.put("INFO: System Started\n"); logBuffer.put("DEBUG: Initializing modules\n"); logBuffer.mark(); // Marking this point logBuffer.put("ERROR: Temporary glitch detected\n"); // Step 2: Reset back to mark if error should be ignored logBuffer.reset(); // Rollback to marked point logBuffer.put("INFO: System Running Smoothly\n"); // Prepare buffer for reading logBuffer.flip(); // Step 3: Simulate writing to file try (FileWriter fw = new FileWriter("logs.txt")) { while (logBuffer.hasRemaining()) { fw.write(logBuffer.get()); } System.out.println("Logs written to logs.txt successfully."); } catch (IOException e) { e.printStackTrace(); } } }
Output File (logs.txt
):
INFO: System Started
DEBUG: Initializing modules
INFO: System Running Smoothly
Code language: HTTP (http)
The Buffer
class in Java NIO is a fundamental building block for handling data in a more efficient and flexible way compared to traditional I/O. It provides a container for a fixed amount of data and supports key properties such as capacity, limit, position, and mark to manage data read/write operations effectively.
As an abstract class, Buffer
is extended by specific buffer types like ByteBuffer
, CharBuffer
, IntBuffer
, etc., each designed to work with a particular primitive type. These buffers are essential when working with channels (FileChannel
, SocketChannel
, etc.), enabling non-blocking, buffered, and high-performance I/O.