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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With