Java - File Input Output Buffer Writing

Introduction

There are two ways to write data to a buffer:

  • Using absolute position
  • Using relative position
  • put() method writes data to a buffer.
  • put() method has five versions: one for absolute position write and four for relative position write.
  • The absolute version of the put() method does not affect the position of the buffer.
  • The relative versions of the put() method write the data and advance the position of the buffer by one for each written element.
Method
Meaning
put(int index, byte b)
writes the specified b data at the specified index. The call to this method does not change the current position of the buffer.
put(byte b)
a relative put() method that writes the specified byte at the current position of the buffer and increments the position by 1.
put(byte[] source, int offset, int length)

reads the length number of bytes from the source array starting at offset and writes them to the buffer starting at the current position.
The position of the buffer is incremented by length.
put(byte[] source)
the same as calling put(byte[] source, 0, source.length).
ByteBuffer put(ByteBuffer src)
reads the remaining bytes from the specified byte buffer src and writes them to the buffer.

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);//from ww w. j a va  2 s  . c om

    // 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

You can read/write data using the relative get() and put() methods if the position of the buffer is less than its limit.

The working range for the absolute read/write is the index between zero and limit -1. So

Related Topics