Convert Reader to InputStream in Java

May 16, 2020 No comments Java IO Conversions Reader InputStream

1. Introduction

In this article we are going to learn how to convert Reader to InputStream using plain Java solution and external libraries like Guava and Apache Commons IO.

If you are looking for more Java I/O related articles, check the following links:

2. Reader to InputStream in plain Java

It is inconceivable that there are no methods in plain Java that converts Reader to InputStream directly, even though the opposite classes: InputStreamReader and OutputStreamWriter are included. So, the solution in plain Java will not be straightforward:

package com.frontbackend.java.io.conversions.toinputstream.fromreader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;

public class ReaderToInputStreamUsingPlainJava {

    public static void main(String[] args) throws IOException {
        Reader reader = new StringReader("frontbackend.com");

        char[] charBuffer = new char[1024];
        StringBuilder builder = new StringBuilder();

        int read;
        while ((read = reader.read(charBuffer, 0, charBuffer.length)) != -1) {
            builder.append(charBuffer, 0, read);
        }

        InputStream inputStream = new ByteArrayInputStream(builder.toString()
                                                                  .getBytes(StandardCharsets.UTF_8));
    }
}

In this example, first, we need to read all characters from given StringReader and aggregate them in StringBuilder. Then, using ByteArrayInputStream we create an instance of InputStream that wraps bytes array taken from String.

Note that every time we convert character-based stream to byte-based stream we should specify the encoding that defines how you wish to represent your characters as bytes.

3. Convert Reader to InputStream using Guava

Let's take a look at a simpler example using Guava library:

package com.frontbackend.java.io.conversions.toinputstream.fromreader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;

import com.google.common.io.CharStreams;

public class ReaderToInputStreamUsingGuava {

    public static void main(String[] args) throws IOException {
        Reader reader = new StringReader("frontbackend.com");

        InputStream inputStream = new ByteArrayInputStream(CharStreams.toString(reader)
                                                                      .getBytes(StandardCharsets.UTF_8));
    }
}

In this approach, we have to read all characters from Reader first. Luckily, Guava comes with dedicated utility CharStream that we can use for this operation. Then, String is converted to byte array and wrapped by ByteArrayInputStream.

4. Reader to InputStream using Apache Commons IO library

Finally, the best solution comes from Apache Commons IO library:

package com.frontbackend.java.io.conversions.toinputstream.fromreader;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.input.ReaderInputStream;

public class ReaderToInputStreamUsingReaderInputStream {

    public static void main(String[] args) throws IOException {
        Reader reader = new StringReader("frontbackend.com");
        InputStream inputStream = new ReaderInputStream(reader, StandardCharsets.UTF_8);
    }
}

Apache Commons IO has a dedicated class - ReaderInputStream for this kind of conversions, so this is a single-line solution.

5. Conclusion

In this article, we presented several ways to convert Reader to InputStream in Java. It is a shame that Java doesn't have a direct solution for this operation, yet. Luckily other libraries have.

Sample snippets used in this tutorial are available under our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}