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 Implement Max Heap
HashMap trong Java hoạt động như thế nào?
Java Program to Implement Knapsack Algorithm
Spring Security – security none, filters none, access permitAll
Java Program to Implement Bubble Sort
Refactoring Design Pattern với tính năng mới trong Java 8
Mapping a Dynamic JSON Object with Jackson
Java Program to Perform Polygon Containment Test
Comparing Two HashMaps in Java
Java Program to Implement Sorted Singly Linked List
Server-Sent Events in Spring
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Serialization và Deserialization trong java
Spring WebClient and OAuth2 Support
Hướng dẫn Java Design Pattern – Abstract Factory
Guava Collections Cookbook
Java Program to Describe the Representation of Graph using Adjacency Matrix
JUnit5 @RunWith
Java Program to Check Whether a Weak Link i.e. Articulation Vertex Exists in a Graph
Java Program to Implement Sieve Of Sundaram
A Quick Guide to Spring Cloud Consul
Java Program to Implement Hash Tables Chaining with List Heads
Custom Error Pages with Spring MVC
Java Program to Implement Triply Linked List
Java Program to Compute DFT Coefficients Directly
Display Auto-Configuration Report in Spring Boot
Write/Read cookies using HTTP and Read a file from the internet
Java Program to Implement Dijkstra’s Algorithm using Queue
Simple Single Sign-On with Spring Security OAuth2
An Example of Load Balancing with Zuul and Eureka
Spring Security Basic Authentication
Java Program to Find a Good Feedback Edge Set in a Graph