You’re writing some code and are faced with converting some unknown length InputStream
containing text to a String
object in Java.
If you are working with JDK 9 (or later), you are in luck as the readAllBytes()
method was added in the InputStream
class. This method provides one-line solution to convert an InputStream
to a byte
array. The byte
array can then simply be decoded into a String
using the String
’s constructor method. The code below is an example of how to use the readAllBytes()
method:
public String toString_ReadAllBytes(InputStream stream) throws Exception { Byte[] stringBytes = stream.readAllBytes(); // read all bytes into a byte array String string = new String(stringBytes); // decodes stringBytes into a String return string; }
It should, however, be noted that the Java API documentation states that this method is not intended for use with larger input streams. However, in practice, we found this method should be fast enough for most applicable use cases. With an input stream of around 1.9 gigabytes, it only took a two seconds to execute this conversion. We did not experiment with anything larger as, in Java, the String
class is based on a 32-bit array and so it cannot be assigned more than two gigabytes of data without throwing an OutOfMemoryError
.
The equivalent code for Java 8 (or lower) is slightly more complex. Without the readAllBytes()
method, the most efficient alternative is to make use of a ByteArrayOutputStream
and using InputStream.read()
to read chunks of data at a time as shown in the example below:
public String toString_ByteArrayOutputStream(InputStream stream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int readBytes = inputStream.read(buffer); // inputStream.read() returns -1 when the end of the stream is reached while(readBytes != -1){ outputStream.write(buffer, 0, readBytes); readBytes = inputStream.read(buffer); } return outputStream.toString(); }
We found this method to be very slightly slower than the JDK 9 readAllBytes()
solution, but still very useable for any size of input streams. Our 1.9 gigabyte input stream processed in around four seconds with this approach compared to the two second execution time achieved by the readAllBytes()
method.
In conclusion, there are many other ways to create a String
from an InputStream
in Java. The above two examples represent the simplest and most efficient of these. If your environment permits later versions of Java (9 or newer), the built in methods provided by the InputStream
class make it trivial to convert between InputStream
and String
. For most situations, this approach has very fast execution and requires little code to get going. Where only older versions of Java are available, the quickest solution is to read the InputStream
in and then write this data to an OutputStream
to produce the final String result.