Java ByteBuffer get byte

Description

Java ByteBuffer get byte

import java.nio.ByteBuffer;

public class Main {
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.allocate(8);
    for (int i = 50; i < 58; i++) {
      bb.put((byte) i);
    }/*ww w . j  a v a 2  s .c  o m*/

    bb.limit(bb.position());
    bb.position(0);

    int limit = bb.limit();
    for (int i = 0; i < limit; i++) {
      byte b = bb.get();
      System.out.println(b);
    }
  }
}
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) + " ");
    }// w  w w.  j av  a2 s.  c om

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