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:

Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Adding a Newline Character to a String in Java
String Operations with Java Streams
Java – Try with Resources
CharSequence vs. String in Java
Composition, Aggregation, and Association in Java
Java Program to Implement Triply Linked List
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Annotation trong Java 8
Java Program to Permute All Letters of an Input String
Java Program to Represent Linear Equations in Matrix Form
A Guide to Iterator in Java
Java Program to Use Dynamic Programming to Solve Approximate String Matching
Java Program to Check the Connectivity of Graph Using BFS
Java Program to Check whether Directed Graph is Connected using BFS
Hướng dẫn Java Design Pattern – Builder
Comparing Strings in Java
Constructor Dependency Injection in Spring
Auditing with JPA, Hibernate, and Spring Data JPA
Java Program to Implement Counting Sort
Hướng dẫn Java Design Pattern – Strategy
Hashtable trong java
Java Program to Check the Connectivity of Graph Using DFS
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Spring Security Login Page with React
How To Serialize and Deserialize Enums with Jackson
Java Program to Generate Random Numbers Using Middle Square Method
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
Java Program to Implement LinkedHashSet API
Daemon Threads in Java
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Java Program to Perform Matrix Multiplication