Here you can find the source of readBytes(InputStream in, long len)
public static byte[] readBytes(InputStream in, long len) throws IOException
//package com.java2s; // This package is part of the Spiralcraft project and is licensed under import java.io.InputStream; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class Main { public static final int DEFAULT_BUFFER_SIZE = 65536; public static byte[] readBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copyRaw(in, out, DEFAULT_BUFFER_SIZE); return out.toByteArray(); }/*from w w w . ja v a2 s.com*/ public static byte[] readBytes(InputStream in, long len) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copyRaw(in, out, DEFAULT_BUFFER_SIZE, len); return out.toByteArray(); } /** * Copy an InputStream to an OutputStream using a buffer of the specified size. */ public static long copyRaw(InputStream in, OutputStream out, int bufferSize) throws IOException { byte[] buffer = new byte[bufferSize]; long count = 0; for (;;) { int read = in.read(buffer, 0, buffer.length); if (read < 0) { break; } out.write(buffer, 0, read); count += read; } return count; } /** * Copy (len) bytes from an InputStream to an OutputStream * using a buffer of the specified size and blocking until the specified * number of bytes is read. */ public static long copyRaw(InputStream in, OutputStream out, int bufferSize, long len) throws IOException { if (bufferSize <= 0) { bufferSize = DEFAULT_BUFFER_SIZE; } byte[] buffer = new byte[bufferSize]; long count = 0; if (len <= 0) { for (;;) { int read = in.read(buffer, 0, buffer.length); if (read < 0) { break; } out.write(buffer, 0, read); count += read; } } else { for (;;) { int read = in.read(buffer, 0, (int) Math.min(buffer.length, len - count)); if (read < 0) { break; } out.write(buffer, 0, read); count += read; if (count == len) { break; } } } return count; } }