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:

Spring Boot - Enabling HTTPS
Converting Between a List and a Set in Java
Upload and Display Excel Files with Spring MVC
Query Entities by Dates and Times with Spring Data JPA
Java Program to Implement the Vigenere Cypher
Java Program to Represent Graph Using Incidence Matrix
Spring Boot - Quick Start
So sánh Array và ArrayList trong Java
Java Program to Implement Johnson’s Algorithm
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Queue using Linked List
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Removing Elements from Java Collections
A Guide to JUnit 5 Extensions
Shuffling Collections In Java
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
StringBuilder vs StringBuffer in Java
Spring Cloud Connectors and Heroku
Cơ chế Upcasting và Downcasting trong java
Check If Two Lists are Equal in Java
Java Program to Check whether Directed Graph is Connected using DFS
Java Program to Implement Triply Linked List
How to Return 404 with Spring WebFlux
Java Program to Find the Minimum value of Binary Search Tree
Java – Generate Random String
Java Program to Implement Min Heap
Java Program to Perform Addition Operation Using Bitwise Operators
Giới thiệu HATEOAS
Java Program to Generate Random Numbers Using Probability Distribution Function
Using a List of Values in a JdbcTemplate IN Clause
Retrieve User Information in Spring Security