Putting Bytes into a ByteBuffer - Java File Path IO

Java examples for File Path IO:ByteBuffer

Description

Putting Bytes into a ByteBuffer

Demo Code

import java.nio.ByteBuffer;

public class Main {
  void m() {/*from  w  ww  .j  av  a 2  s .c  om*/
    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);

    // Get the buffer's capacity
    int capacity = bbuf.capacity(); // 10

    // Use the absolute put().
    // This method does not affect the position.
    bbuf.put((byte) 0xFF); // position=0

    // Set the position
    bbuf.position(5);

    // Use the relative put()
    bbuf.put((byte) 0xFF);

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

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

    // Set the limit
    bbuf.limit(7); // remaining=1

    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7
  }
}

Related Tutorials