Java InputStream to Byte Array getBytesFromInputStream(InputStream inputStream)

Here you can find the source of getBytesFromInputStream(InputStream inputStream)

Description

Extracts the bytes out of an InputStream.

License

LGPL

Parameter

Parameter Description
inputStream The stream from which to extract bytes.

Exception

Parameter Description
IOException Indicates a problem accessing the stream

Return

The bytes

Declaration

public static byte[] getBytesFromInputStream(InputStream inputStream) throws IOException 

Method Source Code

//package com.java2s;
/*/*from   w ww .j av  a2  s . com*/
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */

import java.io.IOException;
import java.io.InputStream;

import java.util.LinkedList;
import java.util.List;

public class Main {
    /**
     * Extracts the bytes out of an InputStream.
     *
     * @param inputStream The stream from which to extract bytes.
     *
     * @return The bytes
     *
     * @throws IOException Indicates a problem accessing the stream
     *
     * @see #getBytesFromInputStreamSafely(java.io.InputStream)
     */
    public static byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
        // Optimized by HHH-7835
        int size;
        final List<byte[]> data = new LinkedList<byte[]>();
        final int bufferSize = 4096;
        byte[] tmpByte = new byte[bufferSize];
        int offset = 0;
        int total = 0;
        for (;;) {
            size = inputStream.read(tmpByte, offset, bufferSize - offset);
            if (size == -1) {
                break;
            }

            offset += size;

            if (offset == tmpByte.length) {
                data.add(tmpByte);
                tmpByte = new byte[bufferSize];
                offset = 0;
                total += tmpByte.length;
            }
        }

        final byte[] result = new byte[total + offset];
        int count = 0;
        for (byte[] arr : data) {
            System.arraycopy(arr, 0, result, count * arr.length, arr.length);
            count++;
        }
        System.arraycopy(tmpByte, 0, result, count * tmpByte.length, offset);

        return result;
    }
}

Related

  1. getBytes(InputStream is)
  2. getBytes(InputStream is)
  3. getBytes(InputStream is, int max_len)
  4. getBytes(InputStream stream)
  5. getBytes(InputStream stream)
  6. getBytesFromInputStream(InputStream inputStream)
  7. getBytesFromInputStream(InputStream inputStream)
  8. getBytesFromInputStream(InputStream is)
  9. getBytesFromInputStream(InputStream is)