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:

A Quick Guide to Spring Cloud Consul
Java Program to Implement D-ary-Heap
Immutable ArrayList in Java
Connect through a Proxy
Java Program to Check whether Graph is Biconnected
HttpClient Basic Authentication
Set Interface trong Java
Migrating from JUnit 4 to JUnit 5
Control Structures in Java
Java Program to Implement Ternary Search Tree
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Comparing Arrays in Java
Java Program to Implement Park-Miller Random Number Generation Algorithm
Java Program to Find Path Between Two Nodes in a Graph
Java Program to Implement Treap
Circular Dependencies in Spring
Apache Commons Collections MapUtils
Spring Boot - OAuth2 with JWT
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
Java Program to Represent Graph Using Incidence List
Guide to Java 8’s Collectors
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Vòng lặp for, while, do-while trong Java
Java Program to Implement the One Time Pad Algorithm
How to Manually Authenticate User with Spring Security
Giới thiệu Google Guice – Injection, Scope
Spring Boot Tutorial – Bootstrap a Simple Application
Working With Maps Using Streams
Hướng dẫn Java Design Pattern – DAO