Java tutorial
//package com.java2s; //License from project: Apache License import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; public class Main { /** * Relative <em>get</em> method for reading {@code size} number of bytes from the current * position of this buffer. * <p> * <p>This method reads the next {@code size} bytes at this buffer's current position, * returning them as a {@code ByteBuffer} with start set to 0, limit and capacity set to * {@code size}, byte order set to this buffer's byte order; and then increments the position by * {@code size}. */ private static ByteBuffer getByteBuffer(final ByteBuffer source, final int size) throws BufferUnderflowException { if (size < 0) { throw new IllegalArgumentException("size: " + size); } final int originalLimit = source.limit(); final int position = source.position(); final int limit = position + size; if ((limit < position) || (limit > originalLimit)) { throw new BufferUnderflowException(); } source.limit(limit); try { final ByteBuffer result = source.slice(); result.order(source.order()); source.position(limit); return result; } finally { source.limit(originalLimit); } } }