36

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.

jthg
  • 2,630
  • 3
  • 26
  • 32

5 Answers5

20

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

zznate
  • 494
  • 2
  • 4
  • 2
    +1 - unless you know what you are doing, reusing a widely used library saves time and effort. – Stephen C Dec 12 '09 at 00:21
  • 2
    I ended up using org.apache.commons.io.IOUtils.toString(InputStream input, String encoding) – jthg Dec 12 '09 at 01:08
  • 2
    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 Dec 12 '09 at 08:58
  • +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 Feb 10 '10 at 21:55
10

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
  • 249,448
  • 50
  • 371
  • 469
  • 3
    +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 Dec 12 '09 at 00:26
  • 4
    It is, unfortunately, a common idiom. But I prefer to avoid tests with side-effects. – erickson Dec 12 '09 at 00:32
1

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()
    }

}
Dónal
  • 176,670
  • 166
  • 541
  • 787
1

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
  • 498,481
  • 72
  • 700
  • 1,075
1

I've found a nice way in Java 8 with streams:

public static String readString(InputStream is) {
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String content = br.lines().reduce("", String::concat);
    return content;
}

As stated above you can swap new InputStreamReader(is) with new InputStreamReader(is, "UTF-8"), but I have no experience with this constructor.

thug-gamer
  • 275
  • 6
  • 9