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:


InputStreams and OutputStreams:
* Reading InputStream into a String

Table Of Contents
8 Arrays
10 Maps
11 Strings
12 InputStreams and OutputStreams
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap