How to fully read InputStream to a String with Default Charset

By Avik, Gaea News Network
Wednesday, November 10, 2010

If you are out there puzzled, knowing not what to do and yet transforming that InputStream to a String with Default Charset is an utmost necessity, then let me tell you don’t just wait around thinking cause its going to take a lot of time for the whole procedure to run. Now, there are a number of ways that can get the job done but here we have tried to keep it simple. The variation arises from the fact as what exactly are you using, it can be Commons IO (FileUtils/IOUtils/CopyUtils) or may be Google-Collections/Guava also Apache commons IOUtils and there are others to name.

Inspite of Java’s maturity and large volume of application libraries, it still lacks a simple way to read InputStream as String. Here is a simple implementation using StringBuilder which is much faster than many implementations on the net using StringWriter which internally uses StringBuffer which is inherently slower than StringBuilder.

// Required imports

private static final int BUF_SIZE = 8192;

public static final String getInputStreamAsString(InputStream is) throws IOException {
char[] buf = new char[BUF_SIZE];
InputStreamReader ir = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int len = 0;
while((len =, 0, BUF_SIZE)) != -1) builder.append(buf, 0, len);
return builder.toString();

Limitation: The size of the String is obviously limited by the memory available to Java virtual machine.

So, did you get success, finally??

will not be displayed