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:
Adding a Newline Character to a String in Java
Quick Guide to Spring Bean Scopes
@Order in Spring
A Guide To UDP In Java
A Guide to the finalize Method in Java
Form Validation with AngularJS and Spring MVC
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Java Program to Implement Interval Tree
Java Program to Implement Skew Heap
Quick Guide to Spring Controllers
Spring – Injecting Collections
New Features in Java 11
Sort a HashMap in Java
Find the Registered Spring Security Filters
XML Serialization and Deserialization with Jackson
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
List Interface trong Java
Java Program to Implement Sieve Of Sundaram
Spring Boot - Scheduling
Java Program to Implement Hamiltonian Cycle Algorithm
Overflow and Underflow in Java
Java Program to Implement Euler Circuit Problem
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Java String to InputStream
HashSet trong Java hoạt động như thế nào?
Creating a Generic Array in Java
Java Program to implement Sparse Vector
XML-Based Injection in Spring
Lớp Properties trong java
How to Kill a Java Thread
Spring MVC Async vs Spring WebFlux
Java Program to Implement ConcurrentSkipListMap API