tags:

views:

350

answers:

4

If I start with a java.io.InputStream, what's the easiest way to read the entire stream out into a String (assuming utf-8)?

This should be pretty easy but I'm mostly a C# person and google is failing me on this. Thanks.

A: 

Reading/writing from streams is remarkably painful in Java.

public static String getStreamContents(InputStream stream) throws IOException {

    StringBuilder content = new StringBuilder()

    Reader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"))
    String lineSeparator = System.getProperty("line.separator");

    try {
        String line
        while ((line = reader.readLine()) != null) {
            content.append(line + lineSeparator)
        }
        return content.toString()

    } finally {
        reader.close()
    }

}
Don
swap new InputStreamReader(stream) with new InputStreamReader(stream, "UTF-8")
Buhb
Your code discards line breaks.
Stephen C
Done, thanks for the tips
Don
your code changes the line breaks. if you have DOS new lines, your string will be shorter.
Peter Lawrey
+6  A: 

Depending on what licenses you are comfortable with, it's a one liner with Jakarta-Commons IO library.

zznate
+1 - unless you know what you are doing, reusing a widely used library saves time and effort.
Stephen C
I ended up using org.apache.commons.io.IOUtils.toString(InputStream input, String encoding)
jthg
I always vote up when people suggest something from the Jakarta Commons. As boring as it is, you still have some business logic to deliver by the end of the day and it doesn't make sense to reinvent the wheel every day.
Ravi Wallau
+1 This is so useful, I have been using java for a long time but I just don't see why I need to play their tedious I/O game.
Zombies
+4  A: 

Do specify the character encoding. Do not waste code, introduce bugs, and slow execution with a BufferedReader.

Here is an example. You could parameterize it with a buffer size, encoding, etc.

static String readString(InputStream is) throws IOException {
  char[] buf = new char[2048];
  Reader r = new InputStreamReader(is, "UTF-8");
  StringBuilder s = new StringBuilder();
  while (true) {
    int n = r.read(buf);
    if (n < 0)
      break;
    s.append(buf, 0, n);
  }
  return s.toString();
}
erickson
+1 - but a common idiom is to write the loop as follows: `int n; while((n = r.read(buf)) >= 0) { s.append(buf, 0, n); }`
Stephen C
It is, unfortunately, a common idiom. But I prefer to avoid tests with side-effects.
erickson
A: 

Using Commons-IO is likely to be the best option. For your interest, another approach is to copy all the bytes and then convert it into a String.

public static String readText(InputStream is, String charset) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] bytes = new byte[4096];
    for(int len;(len = is.read(bytes))>0;)
        baos.write(bytes, 0, len);
    return new String(baos.toByteArray(), charset);
}
Peter Lawrey