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 - Servlet Filter
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Java Program to Find the Longest Path in a DAG
Java Program to Generate Randomized Sequence of Given Range of Numbers
Java Program to Implement Sorted Array
Integer Constant Pool trong Java
Java Program to Implement RoleUnresolvedList API
Quick Guide on Loading Initial Data with Spring Boot
Tìm hiểu về Web Service
Java 8 Stream findFirst() vs. findAny()
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Beans and Dependency Injection
Java – Reader to Byte Array
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Java Program to Implement Interval Tree
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Understanding Memory Leaks in Java
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Recommended Package Structure of a Spring Boot Project
Java Program to Construct K-D Tree for 2 Dimensional Data
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Java Program to Implement Circular Doubly Linked List
Spring Boot - Runners
A Guide to @RepeatedTest in Junit 5
Bootstrapping Hibernate 5 with Spring
Từ khóa throw và throws trong Java
Java Program to Implement Splay Tree
HttpClient with SSL
Java Program to Create a Random Graph Using Random Edge Generation
RegEx for matching Date Pattern in Java
Java Program to Compute DFT Coefficients Directly
Hướng dẫn Java Design Pattern – Interpreter