Java - File Input Output Buffer Reading

Introduction

There are two ways to read data from a buffer:

  • Using absolute position
  • Using relative position

Absolute

In an absolute position read, you specify the index from which to read the data.

The position of the buffer is unchanged after an absolute position read.

Relative

In a relative position read, you set how many data elements to read.

The current position of the buffer determines which data elements will be read.

In a relative position read, the read starts at the current position and it is incremented by one after reading each data element.

The overloaded get() method is used to read data from a buffer.

All buffer classes have the similar method with different primitive types:

Method
Meaning
get(int index)



returns the data at the given index.
For example, get(2) will return the data at index 2 from the buffer.
It is an absolute way of reading data from a buffer.
This method does not change the current position of the buffer.
get()

returns the data from the current position and increases the position by 1.
It is a relative way of reading data from a buffer because you read the data relative to the current position.
get(byte[] destination, int offset, int length)
read data from a buffer in bulk. It is a relative read from a buffer.
get(byte[] destination)


fills the specified destination array by reading data from the current position of the buffer and incrementing the current position by one each time it reads a data element.
It is a relative way of reading data from a buffer.
This method call is the same as calling get(byte[] destination, 0, destination.length).

Demo

import java.nio.ByteBuffer;

public class Main {
  public static void main(String[] args) {
    // Create a byte buffer with a capacity of 8
    ByteBuffer bb = ByteBuffer.allocate(8);

    // Print the buffer info
    System.out.println("After creation:");
    printBufferInfo(bb);//w w w. j  a va 2s .co  m

    // Populate buffer elements from 50 to 57
    for (int i = 50; i < 58; i++) {
      bb.put((byte) i);
    }

    // Print the buffer info
    System.out.println("After populating data:");
    printBufferInfo(bb);
  }

  public static void printBufferInfo(ByteBuffer bb) {
    int limit = bb.limit();
    System.out.println("Position = " + bb.position() + ", Limit = " + limit);

    // Use absolute reading without affecting the position
    System.out.print("Data: ");
    for (int i = 0; i < limit; i++) {
      System.out.print(bb.get(i) + " ");
    }
    System.out.println();
  }
}

Result

Related Topics