Java Language InputStreams and OutputStreams Reading InputStream into a String

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Java Language Question?