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 code units used as char. That is done with an 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 the 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-character 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