Java InputStream to Byte Array inputStreamToByteArray(InputStream stream)

Here you can find the source of inputStreamToByteArray(InputStream stream)

Description

Reads the contents of an stream until exhausted and converts contents to an array of bytes.

License

Open Source License

Parameter

Parameter Description
stream a parameter

Declaration

public static byte[] inputStreamToByteArray(InputStream stream)
        throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//from   w w  w.  j  a v  a 2  s.c  o m
     * Reads the contents of an stream until exhausted and converts contents to an array of bytes.
     *
     * @param stream
     */
    public static byte[] inputStreamToByteArray(InputStream stream)
            throws IOException {
        if (stream == null) {
            return new byte[] {};
        }
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        boolean error = false;
        try {
            int numRead = 0;
            while ((numRead = stream.read(buffer)) > -1) {
                output.write(buffer, 0, numRead);
            }
        } catch (IOException ioe) {
            error = true; // this error should be thrown, even if there is an error closing stream
            throw ioe;
        } catch (RuntimeException re) {
            error = true; // this error should be thrown, even if there is an error closing stream
            throw re;
        } finally {
            try {
                stream.close();
            } catch (IOException ioe) {
                if (!error) {
                    throw ioe;
                }
            }
        }
        output.flush();
        return output.toByteArray();
    }
}

Related

  1. inputStreamToByteArray(InputStream is)
  2. inputStreamToByteArray(InputStream is)
  3. inputStreamToByteArray(InputStream is)
  4. inputStreamToByteArray(InputStream is)
  5. inputStreamToByteArray(InputStream is)
  6. inputStreamToByteArrayOutputStream(final InputStream is)
  7. inputStreamToBytes(final InputStream aInputStream)
  8. inputStreamToBytes(final InputStream ins)
  9. inputStreamToBytes(InputStream in)