Reading InputStream into a String

Download java eBook

Example

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.

Java SE 7
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.

Stats

Contributors: 3
2016-09-14
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook