Nugget Friday – InputStream To String Post Java 9

Uncategorized

It’s Nugget Friday again, and we’re excited to bring you another valuable titbit to our beloved coders! In this instalment of our Friday Nugget series, we’re diving into a common yet essential task for developers, especially when handling data read from a file, network or database: converting an InputStream to a String in Java. Knowing how to do this is crucial for efficiently managing IO and data processing tasks.

The Problem

One of the criticisms of Java has been its tendency to get quite verbose for certain tasks. One of them can be found precisely in the realm of IO. Nearly anything to do with reading and writing binary data was a bit of royal pain. You needed to contend with the not so trivial ceremonial code. As an example, ignore the new HTTP client introduced in Java 11 for a moment (spoiler alert: this will come in a future nugget) and let’s say we are making a call to the Dummy JSON recipe API using the venerable URI class as follows.

InputStream inputStream = new URI("https://dummyjson.com/recipes/search?q=chicken").toURL().openStream();

We have an InputStream that is a binary representation of the data from the API. To convert this to String pre Java 9, you would be doing the following:

try (InputStream inputStream = new URI("https://dummyjson.com/recipes/search?q=chicken").toURL().openStream()) {

try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {

StringBuilder builder = new StringBuilder();

String line;

while ((line = reader.readLine()) != null) {

builder.append(line);

}

String text = builder.toString();

} catch (Exception e) {}

} catch (Exception ex) {}

That is a mouthful, I must admit. You had to contend with two *Reader classes and then a StringBuildder to append the lines from the BufferedReader to. Needless to say, the above code could be made simpler.

The Solution

Java 9 added the readAllbytes method that returns a byte[] to the InputStream class. The String class has a constructor for instantiating a new String object that takes a byte array. 

Pairing these two constructs, we can refactor the above code block to the following:

try (InputStream inputStream = new URI("https://dummyjson.com/recipes/search?q=chicken").toURL().openStream()) {

String response = new String(inputStream.readAllBytes());

System.out.println(response);

} catch (Exception ex) {}

Now that is a breath of fresh air. Easy to read and comprehend without much cognitive overhead. 

So, there you have it. Converting an InputStream to a String has been reduced from needing all the ceremonial *Readers and StringBuilder to just a line. How’s that for readability and conciseness!

That’s it for today. Stay tuned as we break down the steps and share some tips to make your coding life easier with our Nugget Friday. And if you missed last week’s episode, check it out here. Happy Coding!

Comments (0)

Post a comment

Your email address will not be published. Required fields are marked *

Payara needs the contact information you provide to us to contact you about our products and services. You may unsubscribe from these communications at any time. For information on how to unsubscribe, as well as our privacy practices and commitment to protecting your privacy, please review our Legal & Privacy Policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Patrik Dudits presenting at Devoxx Belgium 2025 5 minutes
Cloud & Microservices

Devoxx BE 2025: It Only Starts with a Container & How Abstraction Becomes Reality 

At Devoxx Belgium 2025, I was able to talk about what happens after you build your container. In theory, […]

Blue background with coral and fish. Left text: 'MONTHLY CATCH'. Right: laptop screen with tech tabs and Payara Community logo. 5 minutes
Community

The Payara Monthly Catch – October 2025

Welcome aboard the October issue of The Monthly Catch!As the leaves turn and conference season hits full stride, the […]

The Imperative for Legacy Java Modernization in Banking Cover 2 minutes
Jakarta EE

The $57 Billion Problem: Why Banking’s Java Legacy Crisis Demands Immediate Action

How outdated Java systems are draining budgets and throttling innovation across financial services? Let’s dig in in this blog […]