Lewis D.
—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.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.