Java ByteBuffer set position

Description

Java ByteBuffer set position

import java.nio.ByteBuffer;

public class Main {
  public static void main(String[] argv) throws Exception {
    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);

    // Retrieve the capacity of the ByteBuffer
    int capacity = bbuf.capacity(); // 10
    System.out.println(capacity);

    // The position is not affected by the absolute get() method.
    byte b = bbuf.get(5); // position=0

    // Set the position
    bbuf.position(5);/*from w  w  w  .j  av  a  2  s  .  c o m*/

    // Use the relative get()
    b = bbuf.get();

    // Get the new position
    int pos = bbuf.position(); // 6

    // Get remaining byte count
    int rem = bbuf.remaining(); // 4
    System.out.println(rem);
    

    // Set the limit
    bbuf.limit(7); // remaining=1
     
    rem = bbuf.remaining(); 
    System.out.println(rem);
    
    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7

    rem = bbuf.remaining(); 
    System.out.println(rem);
  }
}



PreviousNext

Related