Java I/O How to - Retrieve all bytes in the buffer








Question

We would like to know how to retrieve all bytes in the buffer.

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 {
    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);

    buf.clear();
    bytes = new byte[buf.capacity()];
    buf.get(bytes, 0, bytes.length);

  }
}