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 Perform Finite State Automaton based Search
Spring 5 and Servlet 4 – The PushBuilder
Java Program to Perform Deletion in a BST
HTTP Authentification and CGI/Servlet
Java Program to Implement Patricia Trie
Từ khóa throw và throws trong Java
Java Program to Implement the Checksum Method for Small String Messages and Detect
Java Program to Generate Date Between Given Range
A Quick Guide to Spring Cloud Consul
Java Program to Implement Cartesian Tree
Exploring the Spring 5 WebFlux URL Matching
A Comparison Between Spring and Spring Boot
Giới thiệu JDBC Connection Pool
Service Registration with Eureka
Java Program to Implement Quick Sort with Given Complexity Constraint
Mapping a Dynamic JSON Object with Jackson
Spring Autowiring of Generic Types
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
How to Remove the Last Character of a String?
Java Program to Find Whether a Path Exists Between 2 Given Nodes
Java Program to Perform Complex Number Multiplication
Lớp Collections trong Java (Collections Utility Class)
Java Program to Implement ConcurrentSkipListMap API
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Working With Maps Using Streams
Remove the First Element from a List
Java Program to Implement Selection Sort
Merging Two Maps with Java 8
Spring 5 Testing with @EnabledIf Annotation
Introduction to Spring Data JPA
Java Program to Implement Graph Structured Stack
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm