In many development projects, we might need to convert an InputStream into a String in java. In this tutorial we will discuss 6 simple and best 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, let us assume "inputStream" is a variable of type InputStream.
InputStream inputStream;
Here are the 6 best ways:
1. Using Java 1.8+ inbuilt Streams package:
String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining("\n"));
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() : "";
}
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);
For this method, Apache commons-io library should be included into your project. You can include it with the below maven link: https://mvnrepository.com/artifact/commons-io/commons-io/2.6
4. Using Google Guava library:
String result = CharStreams.toString(new InputStreamReader(inputStream));
For this method, Guava library should be included into your project. You can include it with the below maven link: https://mvnrepository.com/artifact/com.google.guava/guava/r09
5. Spring Boot style:
String content = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
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: https://mvnrepository.com/artifact/org.springframework/spring-core/5.2.4.RELEASE
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();
These are the 6 easy ways to convert inputStream to string in java. If you have any other better ways to solve this problem, drop your comments below.
Data analytics can be heard without right tools. We are launching a dbt course for beginners with practical hands on project.
First 20 people to signup for the course, will get course for free and next 30 people will get a 50% discount. Make sure to signup here.
- Tip: dbt is never spelled in capital letters.
Make sure you subscribe to our website by subscribing to our mailing list and by following us on Twitter (@thetipseason)