Java I/O How to - Add Bytes into a ByteBuffer








Question

We would like to know how to add Bytes into a ByteBuffer.

Answer

  //from  w  w  w  .j  a  v  a 2 s  .c  om


import java.nio.ByteBuffer;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer bbuf = ByteBuffer.allocate(10);
    int capacity = bbuf.capacity(); // 10
    System.out.println(capacity);
    bbuf.put((byte) 0xFF); 
    bbuf.position(5);
    bbuf.put((byte) 0xFF);
    int pos = bbuf.position(); 
    int rem = bbuf.remaining();
    bbuf.limit(7); 
    bbuf.rewind(); 
  }
}

The code above generates the following result.