Sentry Answers>Java>

How do I Read / Convert an InputStream into a String in Java?

How do I Read / Convert an InputStream into a String in Java?

Lewis D.

The Problem

You’re writing some code and are faced with converting some unknown length InputStream containing text to a String object in Java.

The Solution

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:

Click to Copy
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:

Click to Copy
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.

  • Sentry BlogException Handling in Java (with Real Examples)
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.