Reading InputStream into a String

suggest change

Sometimes you may wish to read byte-input into a String. To do this you will need to find something that converts between byte and the “native Java” UTF-16 Codepoints used as char. That is done with a InputStreamReader.

To speed the process up a bit, it’s “usual” to allocate a buffer, so that we don’t have too much overhead when reading from Input.

public String inputStreamToString(InputStream inputStream) throws Exception {
     StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
      int n;
      while ((n = reader.read(buffer)) != -1) {
           // all this code does is redirect the output of `reader` to `writer` in
           // 1024 byte chunks
           writer.write(buffer, 0, n);
      }
}
return writer.toString();
}

Transforming this example to Java SE 6 (and lower)-compatible code is left out as an exercise for the reader.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents