Java InputStream Copy copyStreamToString(InputStream input)

Here you can find the source of copyStreamToString(InputStream input)

Description

Copy the data from an InputStream to a string using the default charset without closing the stream.

License

Apache License

Exception

Parameter Description
IOException an exception

Declaration

public static String copyStreamToString(InputStream input) throws IOException 

Method Source Code


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

import java.io.BufferedReader;

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

import java.io.StringWriter;

public class Main {
    public static final int DEFAULT_BUFFER_SIZE = 8192;

    /** Copy the data from an {@link InputStream} to a string using the default charset without closing the stream.
     * @throws IOException *//*  www.j  a v a2s . c  om*/
    public static String copyStreamToString(InputStream input) throws IOException {
        return copyStreamToString(input, input.available());
    }

    /** Copy the data from an {@link InputStream} to a string using the default charset.
     * @param approxStringLength Used to preallocate a possibly correct sized StringBulder to avoid an array copy.
     * @throws IOException */
    public static String copyStreamToString(InputStream input, int approxStringLength) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        StringWriter w = new StringWriter(Math.max(0, approxStringLength));
        char[] buffer = new char[DEFAULT_BUFFER_SIZE];

        int charsRead;
        while ((charsRead = reader.read(buffer)) != -1) {
            w.write(buffer, 0, charsRead);
        }

        return w.toString();
    }
}

Related

  1. copyStream(ZipInputStream in, ZipEntry entry)
  2. copyStreamBytes(InputStream is)
  3. copyStreamToByteArray(InputStream in, byte[] dest, int off, int len)
  4. copyStreamToBytes(InputStream inputStream)
  5. copyStreamToString(InputStream input)
  6. copyStreamToString(InputStream input)
  7. copyStreamToString(InputStream inputStream, String encoding)
  8. copyStreamToWriter(InputStream in, Writer out, String encoding, boolean close)
  9. copyStreamToWriter(InputStream inStream, Writer writer)