Java InputStream to Byte Array getBytesFromStream(InputStream is)

Here you can find the source of getBytesFromStream(InputStream is)

Description

get Bytes From Stream

License

Apache License

Declaration

public static byte[] getBytesFromStream(InputStream is) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayOutputStream;

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

public class Main {
    public static byte[] getBytesFromStream(InputStream is) throws Exception {

        InputStreamReader isr = new InputStreamReader(is);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {//from  w w  w.  j  a  v a 2s . c  o  m

            int bytesRead = 0;
            int chunkSize = 10000000;
            byte[] chunk = new byte[chunkSize];
            while ((bytesRead = is.read(chunk)) > 0) {
                byte[] ba = new byte[bytesRead];

                for (int i = 0; i < bytesRead; i++) {
                    ba[i] = chunk[i];
                }

                baos.write(ba, 0, ba.length);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (baos != null)
            return baos.toByteArray();
        else
            throw new Exception("cannot convert stream to bytes");

    }
}

Related

  1. getBytesFromInputStream(InputStream inputStream)
  2. getBytesFromInputStream(InputStream is)
  3. getBytesFromInputStream(InputStream is)
  4. getBytesFromStream(InputStream input)
  5. getBytesFromStream(InputStream inputStream)
  6. getBytesFromStream(InputStream is)
  7. getBytesFromStream(InputStream is)
  8. getBytesFromStream(InputStream is)
  9. getBytesFromStream(InputStream is)