Here you can find the source of readBytes(InputStream is, ByteBuffer buffer)
public static void readBytes(InputStream is, ByteBuffer buffer) throws IOException
//package com.java2s; // See LICENSE.txt for license information import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Main { /**/*from w ww. j a va 2 s . c o m*/ * Reads "length" number of bytes from the specified input stream and returns them * as new {@link ByteBuffer} object. */ public static ByteBuffer readBytes(InputStream is, int length) throws IOException { ByteBuffer bb = null; if (length > 0) { bb = getByteBuffer(length); readBytes(is, bb); } else { bb = getByteBuffer(0); } bb.position(0); return bb; } /** * Reads as many bytes from the input stream into the given ByteBuffer, starting at current * buffer position and ending at the current buffer's limit. */ public static void readBytes(InputStream is, ByteBuffer buffer) throws IOException { byte[] buf = new byte[8192]; while (buffer.remaining() > 0) { int len = Math.min(buf.length, buffer.remaining()); int n = is.read(buf, 0, len); if (n < 0) { break; } buffer.put(buf, 0, n); } } /** Reads as many bytes from the input stream into the specified byte array. */ public static void readBytes(InputStream is, byte[] buffer) throws IOException { readBytes(is, buffer, 0, buffer.length); } /** * Reads up to "length" bytes of data from the input stream into the given byte array, * starting at the specified offset. */ public static void readBytes(InputStream is, byte[] buffer, int offset, int length) throws IOException { int bytesRead = 0; offset = Math.max(0, Math.min(offset, length)); length = Math.min(buffer.length - offset, length); while (bytesRead < length) { int newRead = is.read(buffer, offset + bytesRead, length - bytesRead); if (newRead == -1) { throw new IOException("Unable to read remaining " + (buffer.length - bytesRead) + " bytes"); } bytesRead += newRead; } } /** Returns a fully initialized empty {@link ByteBuffer} in little endian order. */ public static ByteBuffer getByteBuffer(int size) { return ByteBuffer.allocate(Math.max(0, size)).order(ByteOrder.LITTLE_ENDIAN); } /** Returns a {@link ByteBuffer} based on {@code buffer} in little endian order. */ public static ByteBuffer getByteBuffer(byte[] buffer) { if (buffer == null) { buffer = new byte[0]; } return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN); } }