Java ByteBuffer convert remaining byte buffer to byte array

Description

Java ByteBuffer convert remaining byte buffer to byte array

import java.nio.ByteBuffer;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.wrap("demo2s.com".getBytes());
    byte[] byteArray = toBytesRemaining(buf);
    System.out.println(new String(byteArray));
  }/* w  w w. j a  va2  s  .co m*/

  /**
   * Convert remaining byte buffer to byte array.
   *
   * @param buffer
   *          Source byte buffer
   * @return Remaining byte array.
   */
  public static byte[] toBytesRemaining(ByteBuffer buffer) {
    byte[] array = new byte[buffer.remaining()];
    buffer.get(array);
    return array;
  }
}



PreviousNext

Related