How to use ByteBuffer in Java?

ByteBuffer API has been in Java since 1.4. The name itself suggests that these contain bytes of data. The data to be stored in the buffer can be Integer (int, long), Characters (char), Floating value (double), all these are converted into bytes before being stored in the buffer array. ByteBuffer can be of two types-

  • Direct ByteBuffer
  • Non-Direct ByteBuffer

also read:

Direct ByteBuffer: JVM tries to use Native IO operations on buffers which are created as direct i.e it doesnt load the buffer contents into another buffer and instead tries to use the buffer directly.
There are a few essential properties of ByteBuffer:

  • Limit: While writing to a buffer, limit indicates how many more bytes can be written, whereas while reading from a buffer limit indicates how many more bytes can be read.
  • Position: Position tracks how much data is written or can be read from a buffer.
  • Capacity: Capacity specifies the number of bytes a buffer can store.

ByteBuffer provides plethora of methods to fetch data from the buffer and to add data to the buffer. The below code shows the use of those APIs:

import java.nio.ByteBuffer;

public class ByteBufferTest {
  public static void main(String[] args) {

    //Create a directBuffer of size 200 bytes
    ByteBuffer directBuffer = ByteBuffer.allocateDirect(200);
    //Create a nonDirectBuffer of size 200 bytes
    ByteBuffer nonDirectBuffer = ByteBuffer.allocate(200);
    //Get the capacity of the buffer
    System.out.println("Capacity "+nonDirectBuffer.capacity());
    //Get the position of the buffer
    System.out.println("Position "+nonDirectBuffer.position() );
    //Add data of different types to the buffer
    //Get the position of the buffer, would print 14 as its has 14 bytes of data
    System.out.println("Position "+nonDirectBuffer.position() );
    //Fetch the data from buffer
    //A char is of 2 bytes, so fetch the integer at index 0+2=2bytes
    //A int is of 4 bytes so fetch the double value at index 2+4=6bytes
    //A double is of 8 bytes so fetch the float value at index 6+8=14bytes

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!