DEV Community

Cover image for How to read or convert an inputstream into a string in java? - Six easy ways
Tip Season
Tip Season

Posted on • Originally published at tipseason.com

How to read or convert an inputstream into a string in java? - Six easy ways

In many development projects, we might need to convert an InputStream into a String in java.
In this tutorial we will discuss simple and handpicked ways to read or convert an InputStream into a String in Java.
Depending upon your project configuration, you can use any of the following methods.

For the purpose of this tutorial, lets assume "inputStream" is a variable of type InputStream.

InputStream inputStream; 
Enter fullscreen mode Exit fullscreen mode

Check the ways below.

1. Using Java 1.8+ inbuilt Streams package:
String result = new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining("\n"));
Enter fullscreen mode Exit fullscreen mode

This method works with Java 1.8+

2. Native Java Scanner way:
try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A")) {
    String result = scanner.hasNext() ? scanner.next() : "";
}
Enter fullscreen mode Exit fullscreen mode

Note that "\A" represents regex pattern for useDelimiter scanner method.
"\A" stands for :start of a string! . So when this pattern is supplied, whole stream is ready into the scanner object.

3. Apache commons-io IOUtils way:
String result = IOUtils.toString(inputStream);
Enter fullscreen mode Exit fullscreen mode

For this method, Apache commons-io library should be included into your project. You can include it with the below maven
maven link.

4. Using Google Guava library:
String result = CharStreams.toString(new InputStreamReader(inputStream));
Enter fullscreen mode Exit fullscreen mode

For this method, Guava library should be included into your project. You can include it with the below maven
maven link

5. Spring Boot style:

String content = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
Enter fullscreen mode Exit fullscreen mode

If you are using spring boot framework for your project you can use this. To include spring boot, you can use the below
maven repo

6. Plain old ByteArrayOutputStream way:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
    baos.write(buffer, 0, length);
}
String result = baos.toString();
Enter fullscreen mode Exit fullscreen mode

If you want to play around with actual InputStreams without any utility methods you can use the above style.

Bonus: How to read and write to file as a string in java in simple way : https://tipseason.com/how-to-read-file-as-string-in-java/

Tech interviews can be challenging if you don't practice the right set of questions. Follow our group for daily interview practice questions.

Top comments (0)