I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

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 Baeldung.

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.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Sort by:   newest | oldest | most voted
Mark Slater
Guest
The Commons IO implementation is totally incorrect – running the code on my machine, I get a byte array representing the UTF-8 characters for “[email protected]”. Note that Commons IO provides a class specifically for this purpose – try: InputStream targetStream = new ReaderInputStream(initialReader, Charsets.UTF_8); I’d also be very cautious of using the suggested implementation using Guava – it reads the *entire* Reader data to a String before turning that entire String into a byte array. Although that might be OK if you happen to know that your Reader just wraps a String literal you declared the line above, in general… Read more »
Eugen Paraschiv
Guest

Hey Mark – that’s odd – I added 2 simple tests that actually check the value and they seem fine. Let me know if they work for you as well, and if they don’t, I’ll look into it further.

And, about the Guava implementation, yes – it’s not very memory efficient. However, this is very much an intro level article – so efficiency isn’t the focus. Here’s one where I did focus on a more efficient way of going through a large file.
Hope that helps. Cheers,
Eugen.

Mark Slater
Guest
Hi Eugen. Looking at your new tests, I see what you intended to do. On line 7 of your Commons IO example, you call initialReader.toString() – i.e. you’re calling toString() on the StringReader you created on line 4. Judging from your new tests, I suspect you intended to call IOUtils.toString(initialReader). Incidentally, the decision made by the Commons IO team to name their method toString has the whiff of bad practice to my mind – choosing a method name defined on Object but which has a different purpose is inviting the kind of bug you’ve encountered. Personally, I still wouldn’t recommend… Read more »
Eugen Paraschiv
Guest
Oh, now I see it. Yes indeed – that was a problem 🙂 Yeah, it’s not the best naming they could have gone with. Now, the conversion might be unusual – but given the fact that the article is only focused on this particular conversion, I’d say that – they’re only going to hit this article if they’re specifically looking for it 🙂 At least that’s what I would assume. The Guava upcoming API looks interesting – I’ll have to check that out when they release it – and maybe update the article as well. It definitely doesn’t come across… Read more »