Java InputStream to Byte Array getBytesFromStream(InputStream is)

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

Description

Convert the inputstream into a byte array.

License

Academic Free License

Parameter

Parameter Description
is a parameter

Declaration

public static byte[] getBytesFromStream(InputStream is) 

Method Source Code

//package com.java2s;
//License from project: Academic Free License 

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**/*from   ww  w . j  a v a2s. c om*/
     * Convert the inputstream into a byte array.
     * 
     * @param is
     * @return
     */
    public static byte[] getBytesFromStream(InputStream is) {
        return getBytesFromStream(is, 2048);
    }

    /**
     * Convert the inputstream into a byte array.
     * 
     * @param is
     * @return
     */
    @SuppressWarnings("unchecked")
    public static byte[] getBytesFromStream(InputStream is, int bufSize) {
        byte ba[] = new byte[bufSize];

        try {
            List bytes = new ArrayList();
            List lengths = new ArrayList();

            int tot = 0;
            int numRead = is.read(ba);
            while (numRead > 0) {
                tot += numRead;
                bytes.add(ba);
                lengths.add(new Integer(numRead));
                ba = new byte[bufSize];
                numRead = is.read(ba);
            }

            ba = new byte[tot];
            byte baTmp[] = null;

            int offset = 0;
            int size = bytes.size();
            for (int i = 0; i < size; i++) {
                baTmp = (byte[]) bytes.get(i);
                numRead = ((Integer) lengths.get(i)).intValue();
                /*
                numRead = baTmp.length;
                if(offset + numRead > tot)
                {
                   numRead = tot-offset;
                }
                */
                System.arraycopy(baTmp, 0, ba, offset, numRead);

                offset += numRead;
            }
            bytes.clear();
            lengths.clear();
            bytes = null;
            lengths = null;
        } catch (Exception ex) {
            ba = null;
            ex.printStackTrace();
        }

        return ba;
    }
}

Related

  1. getBytesFromInputStream(InputStream is)
  2. getBytesFromStream(InputStream input)
  3. getBytesFromStream(InputStream inputStream)
  4. getBytesFromStream(InputStream is)
  5. getBytesFromStream(InputStream is)
  6. getBytesFromStream(InputStream is)
  7. getBytesFromStream(InputStream is)
  8. getBytesFromStream(InputStream is)
  9. getInputStreamAsByteArray(InputStream stream, int length)