Java InputStream Read All readAll(InputStream in)

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

Description

Read an entire stream and return byte[].

License

Open Source License

Parameter

Parameter Description
in inputstream to devour

Exception

Parameter Description
IOException on error from given inputstream

Return

byte[] of data read

Declaration

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

Method Source Code

//package com.java2s;
// Refer to LICENSE for terms and conditions of use.

import java.io.*;

public class Main {
    /**/* ww  w. j a  v  a  2 s  . c o  m*/
     * Read an entire stream and return byte[].
     *
     * @param in inputstream to devour
     * @return byte[] of data read
     * @throws IOException on error from given inputstream
     */
    public static byte[] readAll(InputStream in) throws IOException {
        final int CHUNK = 16 * 1024;
        int total = 0;
        byte[] buf = new byte[CHUNK * 2];
        int read = in.read(buf);
        if (read > 0)
            total += read;
        while (read != -1) {
            if (buf.length - total < CHUNK) {
                byte[] buf2 = new byte[buf.length * 2];
                System.arraycopy(buf, 0, buf2, 0, total);
                buf = buf2;
            }
            read = in.read(buf, total, CHUNK);
            if (read > 0)
                total += read;
        }
        byte[] buf2 = new byte[total];
        System.arraycopy(buf, 0, buf2, 0, total);
        return buf2;
    }
}

Related

  1. readAll(final InputStream is)
  2. readAll(InputStream i, byte b[])
  3. readAll(InputStream in)
  4. readall(InputStream in)
  5. readAll(InputStream in)
  6. readAll(InputStream in)
  7. readAll(InputStream in)
  8. readAll(InputStream in, byte[] buffer, int off, int len)