Java – Reader to InputStream

In this quick tutorial we’re going to look at the conversion from a Reader to an InputStream – first with plain Java, then with Guava and finally with the Apache Commons IO library.

This article is part of the “Java – Back to Basic” series here on VietMX’s Blog.

1. With Java

Let’s start with the Java solution:

@Test
public void givenUsingPlainJava_whenConvertingReaderIntoInputStream_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("With Java");

    char[] charBuffer = new char[8 * 1024];
    StringBuilder builder = new StringBuilder();
    int numCharsRead;
    while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) {
        builder.append(charBuffer, 0, numCharsRead);
    }
    InputStream targetStream = new ByteArrayInputStream(
      builder.toString().getBytes(StandardCharsets.UTF_8));

    initialReader.close();
    targetStream.close();
}

Notice that we’re reading (and writing) chunks of data at a time.

2. With Guava

Next – let’s look at the much simpler Guava solution:

@Test
public void givenUsingGuava_whenConvertingReaderIntoInputStream_thenCorrect() 
  throws IOException {
    Reader initialReader = new StringReader("With Guava");

    InputStream targetStream = 
      new ByteArrayInputStream(CharStreams.toString(initialReader)
      .getBytes(Charsets.UTF_8));

    initialReader.close();
    targetStream.close();
}

Notice that we’re using an out of the box input stream which turns the entire conversion into a one liner.

3. With Commons IO

Finally – let’s look at the Commons IO solution – also a simple one liner:

@Test
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() 
  throws IOException {
    Reader initialReader = new StringReader("With Commons IO");

    InputStream targetStream = 
      IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);

    initialReader.close();
    targetStream.close();
}

Note that we’re here dealing with any kind of Reader – but if you’re working specifically with text data, it’s always a good idea to specify the charset explicitly rather than use the JVM default.

And there you have it – 3 simple ways to transform the Reader into an InputStream. Make sure to check out the sample over on GitHub.

Related posts:

Introduction to Spring Cloud OpenFeign
Limiting Query Results with JPA and Spring Data JPA
Creating a Custom Starter with Spring Boot
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Find the Registered Spring Security Filters
Java Program to Generate Random Numbers Using Middle Square Method
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Mệnh đề if-else trong java
Spring Data Reactive Repositories with MongoDB
Java Program to Implement Pagoda
Java 8 Stream findFirst() vs. findAny()
Java Program to Implement Randomized Binary Search Tree
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Java Program to Implement Radix Sort
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Spring @Primary Annotation
The Spring @Controller and @RestController Annotations
Object cloning trong java
A Guide to TreeSet in Java
Java Program to Implement Range Tree
Java Program to Implement PriorityBlockingQueue API
Java Program to Implement SimpeBindings API
Login For a Spring Web App – Error Handling and Localization
Java Program to Implement Hash Tables Chaining with Binary Trees
Java Program to Find the Peak Element of an Array O(n) time (Naive Method)
JUnit5 Programmatic Extension Registration with @RegisterExtension
Using a Spring Cloud App Starter
Java Program to Implement Binary Heap
Java Program to Decode a Message Encoded Using Playfair Cipher
Most commonly used String methods in Java
Server-Sent Events in Spring
Sử dụng Fork/Join Framework với ForkJoinPool trong Java