Java ByteBuffer get sub buffer from offset and length

Description

Java ByteBuffer get sub buffer from offset and length


import java.nio.ByteBuffer;
import java.util.Arrays;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer bb = ByteBuffer.wrap("demo2s.com".getBytes());
    /*from  w w w  .j a  v a2s. c  om*/
    System.out.println(Arrays.toString(toArray(bb)));
    ByteBuffer newBB = slice(bb, 2,3);
    
    System.out.println(Arrays.toString(toArray(newBB)));
  }

  public static ByteBuffer slice(final ByteBuffer buffer,
      final int position, final int size) {
  final ByteBuffer tmp = buffer.duplicate();
  tmp.position(position).limit(position + size);
  return tmp.slice();
}
  public static byte[] toArray(final ByteBuffer buffer) {
    byte[] array = new byte[buffer.limit()];
    buffer.get(array);
    return array;
  }
}



PreviousNext

Related