Java ByteBuffer store byte

Description

Java ByteBuffer store byte

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
    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) + " ");
    }/*from w  w  w .  j a va  2  s.  com*/

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

    limit = bb.limit();
    System.out.println("\nPosition = " + 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) + " ");
    }
  }
}



PreviousNext

Related