Java InputStream to Byte Array inputStreamToBytes(InputStream in)

Here you can find the source of inputStreamToBytes(InputStream in)

Description

Reads all bytes from the given input stream and returns a byte array.

License

Apache License

Parameter

Parameter Description
in the input stream to read

Exception

Parameter Description
IOException if the data cannot be read

Return

the data read from the input stream

Declaration

public static byte[] inputStreamToBytes(InputStream in) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2006 - 2012 Vienna University of Technology,
 * Department of Software Technology and Interactive Systems, IFS
 * // w  ww .  j a  va 2  s  . c  om
 * 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.
 ******************************************************************************/

import java.io.ByteArrayOutputStream;

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

public class Main {
    private static final int WRITE_BUFFER_SIZE = 1024;

    /**
     * Reads all bytes from the given input stream and returns a byte array.
     * 
     * @param in
     *            the input stream to read
     * @return the data read from the input stream
     * @throws IOException
     *             if the data cannot be read
     */
    public static byte[] inputStreamToBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream(WRITE_BUFFER_SIZE);
        byte[] buffer = new byte[WRITE_BUFFER_SIZE];
        int len;

        try {
            while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
            }
        } finally {
            out.close();
            in.close();
        }

        return out.toByteArray();
    }
}

Related

  1. inputStreamToByteArray(InputStream stream)
  2. inputStreamToByteArrayOutputStream(final InputStream is)
  3. inputStreamToBytes(final InputStream aInputStream)
  4. inputStreamToBytes(final InputStream ins)
  5. inputStreamToBytes(InputStream in)
  6. inputStreamToBytes(InputStream in)
  7. inputStreamToBytes(InputStream is)
  8. loadByteCode(String name, final InputStream is)