Java - Read all from buffer using a relative position read after finishing writing

Introduction

Set the limit of the buffer equal to its position and set its position to 0.

Demo

import java.nio.ByteBuffer;

public class Main {
  public static void main(String[] args) {
    // Create a byte buffer of capacity 8 and populate its elements
    ByteBuffer bb = ByteBuffer.allocate(8);
    for (int i = 50; i < 58; i++) {
      bb.put((byte) i);
    }/* w w  w. j  a  va  2 s  .com*/

    // Set the limit the same as the position and set the position to 0
    bb.limit(bb.position());
    bb.position(0);

    // Now bb is set to read all data using relative get() method
    int limit = bb.limit();
    for (int i = 0; i < limit; i++) {
      byte b = bb.get(); // Uses a relative read
      System.out.println(b);
    }
  }
}

Result

Related Topic