Java I/O How to - Use while loop to read a ByteBuffer








Question

We would like to know how to use while loop to read a ByteBuffer.

Answer

import java.nio.ByteBuffer;
/*  www  .j a  va2 s.  c  o m*/
public class MainClass {
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, 'a' });
    bb.rewind();
    System.out.println("Byte Buffer");
    while (bb.hasRemaining())
      System.out.println(bb.position() + " -> " + bb.get());
  }
}

The code above generates the following result.