Java ByteArrayOutputStream Write readAll(InputStream in)

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

Description

Reads the complete InputStream into a String.

License

Open Source License

Parameter

Parameter Description
in The <code>InputStream</code> to read from

Exception

Parameter Description
IOException an exception

Return

The created String

Declaration

public static String readAll(InputStream in) throws IOException 

Method Source Code

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

import java.io.ByteArrayOutputStream;

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

public class Main {
    /**/*from w  w  w.j  a v a  2s  . c o m*/
     * Reads the complete InputStream into a String.
     * 
     * @param in
     *            The <code>InputStream</code> to read from
     * @param size
     *            The length of the <code>InputStream</code> or <code>-1</code>
     *            if unknown.
     * @return The created String
     * @throws IOException
     */
    public static String readAll(InputStream in, int size) throws IOException {
        byte[] initialBytes;

        if (size < 0) {
            initialBytes = new byte[in.available()];
        } else {
            initialBytes = new byte[size];
        }

        in.read(initialBytes);

        byte[] furtherBytes = new byte[0];
        // check that all input has been read
        char currentChar = (char) -1;
        if ((currentChar = (char) in.read()) != (char) -1) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            out.write(currentChar);

            while ((currentChar = (char) in.read()) != (char) -1) {
                // read rest of the inputStream
                out.write(currentChar);
            }

            furtherBytes = out.toByteArray();
        }

        return new String(initialBytes) + new String(furtherBytes);
    }

    /**
     * Reads the complete InputStream into a String. If the size of the
     * <code>InputStream</code> can be obtained
     * <code>readAll(InputStream in, int size)</code> should be used for safer
     * results.
     * 
     * @param in
     *            The <code>InputStream</code> to read from
     * @return The created String
     * @throws IOException
     */
    public static String readAll(InputStream in) throws IOException {
        return readAll(in, -1);
    }
}

Related

  1. loadStream(InputStream in, String encoding)
  2. readAll(File file)
  3. readAll(InputStream aInputStream)
  4. readAll(InputStream bytes)
  5. readAll(InputStream bytes, int bufferSize)
  6. readAll(InputStream in)
  7. readAll(InputStream in)
  8. readAll(InputStream in)
  9. readAll(InputStream in)