ByteBuffer

ByteBuffer is a concrete subclass of Buffer (from java.nio) that is used for handling byte data in a fast, efficient, and non-blocking way. It’s part of Java NIO (New I/O) and allows direct or indirect memory management.

Commonly Used Methods

Simple Program using ByteBuffer

import java.nio.ByteBuffer;

public class SimpleByteBufferDemo {
    public static void main(String[] args) {
        // Allocate a buffer of 10 bytes
        ByteBuffer buffer = ByteBuffer.allocate(10);

        // Put bytes into buffer
        for (byte i = 1; i <= 5; i++) {
            buffer.put(i);
        }

        // Flip buffer to switch to reading mode
        buffer.flip();

        System.out.println("Reading bytes from buffer:");
        while (buffer.hasRemaining()) {
            System.out.println("Byte: " + buffer.get());
        }
    }
}

Problem Statement:

LotusJavaPrince is building a chat application. Mahesh suggests using ByteBuffer to temporarily store outgoing messages before sending them over the network. The app should:

  • Store a message in a ByteBuffer
  • Use flip() to prepare for reading
  • Simulate converting to a byte array
  • Allow rewinding for resending if the first attempt fails.
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class ChatBufferSimulator {
    public static void main(String[] args) {
        String message = "Hello from LotusJavaPrince to Mahesh!";
        System.out.println("Original Message: " + message);

        // Convert message to bytes
        byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);

        // Wrap bytes into ByteBuffer
        ByteBuffer buffer = ByteBuffer.wrap(messageBytes);

        // Flip not needed since wrap sets position = 0 and limit = messageBytes.length
        sendMessage(buffer);

        // Rewind for resending
        buffer.rewind();
        System.out.println("\nResending the same message...");
        sendMessage(buffer);
    }

    private static void sendMessage(ByteBuffer buffer) {
        System.out.print("Sending message: ");
        while (buffer.hasRemaining()) {
            // Simulate sending each byte
            System.out.print((char) buffer.get());
        }
        System.out.println();
    }
}

Output

Original Message: Hello from LotusJavaPrince to Mahesh!
Sending message: Hello from LotusJavaPrince to Mahesh!

Resending the same message...
Sending message: Hello from LotusJavaPrince to Mahesh!Code language: JavaScript (javascript)

The ByteBuffer class in Java NIO is a powerful tool for handling binary data with high efficiency and fine-grained control. It allows developers to read and write bytes directly into memory without the overhead of stream-based I/O, making it ideal for performance-critical applications such as file I/O, memory-mapped files, and network programming.

By utilizing core properties like position, limit, and capacity, and methods like flip(), clear(), and rewind(), ByteBuffer facilitates precise control over data flow. Additionally, it supports both heap-based and direct buffers, the latter allowing faster native I/O operations at the cost of memory management complexity.

Scroll to Top