Table of Contents
In this quick tutorial we’re going to take a look at converting an InputStream to a Reader using Java, then Guava and finally Apache Commons IO.
This article is part of the “Java – Back to Basic” series here on VietMX’s Blog.
1. With Java
First, let’s look at the simple Java solution – using the readily available InputStreamReader:
@Test public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { InputStream initialStream = new ByteArrayInputStream("With Java".getBytes()); Reader targetReader = new InputStreamReader(initialStream); targetReader.close(); }
2. With Guava
Next – let’s take a look at the Guava solution – using an intermediary byte array and String:
@Test public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream(); byte[] buffer = ByteStreams.toByteArray(initialStream); Reader targetReader = CharSource.wrap(new String(buffer)).openStream(); targetReader.close(); }
Note that the Java solution is simpler than this approach.
3. With Commons IO
Finally – the solution using Apache Commons IO – also using an intermediary String:
@Test public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { InputStream initialStream = IOUtils.toInputStream("With Commons IO"); byte[] buffer = IOUtils.toByteArray(initialStream); Reader targetReader = new CharSequenceReader(new String(buffer)); targetReader.close(); }
And there you have it – 3 quick ways to convert the input stream to a Java Reader. Make sure to check out the sample over on GitHub.
Related posts:
Simple Single Sign-On with Spring Security OAuth2
Creating a Custom Starter with Spring Boot
Spring Boot - Database Handling
Guide to Character Encoding
Java Program to Perform Partial Key Search in a K-D Tree
Hướng dẫn Java Design Pattern – Template Method
Create Java Applet to Simulate Any Sorting Technique
The Registration API becomes RESTful
Java Program to Implement Counting Sort
Spring – Injecting Collections
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Handling Errors in Spring WebFlux
Send email with authentication
Java Program to Implement Max Heap
Java Program to Implement SynchronosQueue API
Testing an OAuth Secured API with Spring MVC
Using Optional with Jackson
A Guide to the finalize Method in Java
MyBatis with Spring
Java Program to Find the Longest Path in a DAG
Comparing Dates in Java
Java Program to Implement K Way Merge Algorithm
Spring Cloud AWS – EC2
Hướng dẫn sử dụng Lớp FilePermission trong java
Java Program to Generate a Random Subset by Coin Flipping
What is Thread-Safety and How to Achieve it?
Java Program to Generate Randomized Sequence of Given Range of Numbers
Tính kế thừa (Inheritance) trong java
A Guide to Java HashMap
Compare Two JSON Objects with Jackson
Spring Cloud Series – The Gateway Pattern
Weak References in Java