Here you can find the source of readAllFrom(java.io.InputStream is)
Parameter | Description |
---|---|
is | The input stream to read. |
public static byte[] readAllFrom(java.io.InputStream is) throws java.io.IOException
//package com.java2s; /* Copyright (c) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.// w w w. j a v a 2 s . c o m */ public class Main { /** Reads an input stream til EOF and returns all bytes read. * The stream will NOT be closed. * * @param is The input stream to read. * @return An array of bytes that represents all bytes read * from the stream until the end-of-file is reached. */ public static byte[] readAllFrom(java.io.InputStream is) throws java.io.IOException { byte[] buf = new byte[8192]; int i = 0; int n = 0, r; final int SIZE = 4096; while (true) { // invariant: buf[0..n-1] has the valid data // and buffer capacity is >= n // make sure buffer has capacity at least n + SIZE while (buf.length <= n + SIZE + 1) buf = resizeVec(buf, 2 * buf.length); // read into buf r = is.read(buf, n, SIZE); if (r <= 0) break; // end of stream n += r; } // resize the byte array to its correct size return resizeVec(buf, n); } private static byte[] resizeVec(byte[] b, int newSize) { byte[] c = new byte[newSize]; System.arraycopy(b, 0, c, 0, b.length > newSize ? newSize : b.length); return c; } }