Java ByteBuffer get sub buffer from offset to end

Description

Java ByteBuffer get sub buffer from offset to end

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());
    /*  www .  j  av a2s.c o m*/
    System.out.println(Arrays.toString(toArray(bb)));
    ByteBuffer newBB = slice(bb, 2);
    
    System.out.println(Arrays.toString(toArray(newBB)));
  }

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



PreviousNext

Related