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:
Java Program to Perform Preorder Recursive Traversal of a Given Binary Tree
Java Program to Implement VList
Guide to Guava Table
Jackson Exceptions – Problems and Solutions
Removing all Nulls from a List in Java
Show Hibernate/JPA SQL Statements from Spring Boot
New Features in Java 11
Java Program to Implement Hash Trie
Introduction to the Functional Web Framework in Spring 5
Spring Cloud AWS – EC2
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Lớp Arrarys trong Java (Arrays Utility Class)
Set Interface trong Java
Checking for Empty or Blank Strings in Java
Abstract class và Interface trong Java
Lớp LinkedHashMap trong Java
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Java Program to Perform the Shaker Sort
Java Deep Learning Essentials - Yusuke Sugomori
Mệnh đề Switch-case trong java
CyclicBarrier in Java
Spring Boot With H2 Database
Java Program to Implement Stack
Java Program to Implement Skip List
Instance Profile Credentials using Spring Cloud
A Guide to the Java LinkedList
Java Program to Find Path Between Two Nodes in a Graph
A Guide to JUnit 5 Extensions
Difference Between Wait and Sleep in Java
Java Program to Find the Mode in a Data Set
Constructor Injection in Spring with Lombok
Java Program to Implement Radix Sort