Java - File Input Output Buffer Creation

Introduction

When you create a buffer, all elements of the buffer are initialized to a value of zero.

Each element of a buffer has an index.

The first element has an index of 0 and the last element has an index of capacity ? 1.

You can create a buffer by using the allocate() factory method:

// Create a byte buffer with the capacity as 8
ByteBuffer bb = ByteBuffer.allocate(8);

// Assigns 8 to the capacity variable
int capacity = bb.capacity();

// Create a character buffer with the capacity as 1024
CharBuffer cb = CharBuffer.allocate(1024);

Byte buffer creation

A byte buffer method allocateDirect() creates a byte buffer from the operating system memory, not from the JVM heap.

You should use a direct byte buffer when a buffer is long-lived.

You can use the isDirect() method of the ByteBuffer class to check if a buffer is direct or non-direct.

// Create a direct byte buffer of 512 bytes capacity
ByteBuffer bbd = ByteBuffer.allocateDirect(512);

Another way to create a buffer is to wrap an array using the buffer's static wrap() method, like so:

// Have an array of bytes
byte[] byteArray = new byte[512];

// Create a byte buffer by wrapping the byteArray
ByteBuffer bb = ByteBuffer.wrap(byteArray);