Java InputStream to Byte Array getBytes(InputStream attachment)

Here you can find the source of getBytes(InputStream attachment)

Description

Reads all bytes from an InputStream

License

Apache License

Parameter

Parameter Description
attachment a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static byte[] getBytes(InputStream attachment) throws IOException 

Method Source Code


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

import java.io.*;

public class Main {
    /**/*from   w w  w.j  a  v a  2  s  .com*/
     * Reads all bytes from an InputStream
     *
     * @param attachment
     * @throws IOException
     */
    public static byte[] getBytes(InputStream attachment) throws IOException {
        ByteArrayOutputStream read = new ByteArrayOutputStream();
        copyBuffer(attachment, read, 2056);
        return read.toByteArray();
    }

    /**
     * Copies an inputstream to an output stream
     *
     * @param in
     * @param out
     * @param bufferSize
     * @throws IOException
     */
    public static void copyBuffer(BufferedInputStream in, BufferedOutputStream out, int bufferSize)
            throws IOException {
        while (in.available() > 0) {
            out.write(in.read());
        }
        in.close();
        out.flush();
        out.close();
    }

    /**
     * Copies an inputstream to an output stream
     *
     * @param in
     * @param out
     * @param bufferSize
     * @throws IOException
     */
    public static void copyBuffer(InputStream in, OutputStream out, int bufferSize) throws IOException {

        byte[] buffer = new byte[bufferSize];

        try {

            while (true) {
                int amountRead = in.read(buffer);
                if (amountRead == -1) {
                    break;
                }
                out.write(buffer, 0, amountRead);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * Reads data from BufferedReader into a String
     *
     * @param reader
     * @throws IOException
     */
    public static String read(BufferedReader reader) throws IOException {
        StringBuffer tmp = new StringBuffer();
        String tmpS;
        while ((tmpS = reader.readLine()) != null) {
            tmp.append(tmpS);
        }
        return tmp.toString();
    }
}

Related

  1. fread(short[] data, int length, InputStream fp)
  2. getBytes(InputStream fis)
  3. getBytes(InputStream in)
  4. getBytes(InputStream in)
  5. getBytes(InputStream in)