Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String from InputStream [duplicate]

Tags:

java

stream

Possible Duplicates:
How do I convert an InputStream to a String in Java?
In Java how do a read an input stream in to a string?

I have an InputSteam and need to simply get a single simple String with the complete contents.

How is this done in Java?

like image 775
Ian Vink Avatar asked Aug 13 '10 17:08

Ian Vink


1 Answers

Here is a modification of Gopi's answer that doesn't have the line ending problem and is also more effective as it doesn't need temporary String objects for every line and avoids the redundant copying in BufferedReader and the extra work in readLine().

public static String convertStreamToString( InputStream is, String ecoding ) throws IOException
{
    StringBuilder sb = new StringBuilder( Math.max( 16, is.available() ) );
    char[] tmp = new char[ 4096 ];

    try {
       InputStreamReader reader = new InputStreamReader( is, ecoding );
       for( int cnt; ( cnt = reader.read( tmp ) ) > 0; )
            sb.append( tmp, 0, cnt );
    } finally {
        is.close();
    }
    return sb.toString();
}
like image 188
x4u Avatar answered Oct 06 '22 01:10

x4u