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 Implement Graph Coloring Algorithm
Hướng dẫn Java Design Pattern – Abstract Factory
Spring 5 Testing with @EnabledIf Annotation
Introduction to Java Serialization
Java Map With Case-Insensitive Keys
Convert String to int or Integer in Java
Spring MVC Setup with Kotlin
Java Program to Convert a Decimal Number to Binary Number using Stacks
An Intro to Spring Cloud Security
Hướng dẫn Java Design Pattern – Factory Method
Giới thiệu Aspect Oriented Programming (AOP)
Spring Boot - Google Cloud Platform
Tính trừu tượng (Abstraction) trong Java
Java – Combine Multiple Collections
MyBatis with Spring
Java Program to Implement vector
Using a Mutex Object in Java
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Java – Convert File to InputStream
Java – Byte Array to Reader
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Bootstrapping Hibernate 5 with Spring
Java Program to Implement the MD5 Algorithm
Java Program to Implement Binomial Heap
Hướng dẫn Java Design Pattern – Adapter
Object Type Casting in Java
Quick Intro to Spring Cloud Configuration
Hướng dẫn Java Design Pattern – Singleton
Custom Error Pages with Spring MVC
File Upload with Spring MVC
Send email with SMTPS (eg. Google GMail)