I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

In this quick tutorial we’re going to take a look at converting an InputStream to a Reader using Java, then Guava and finally Apache Commons IO.

This article is part of the “Java – Back to Basic” series here on Baeldung.

1. With Java

First, let’s look at the simple Java solution – using the readily available InputStreamReader:

@Test
public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect() 
  throws IOException {
    InputStream initialStream = new ByteArrayInputStream("With Java".getBytes());
    
    Reader targetReader = new InputStreamReader(initialStream);

    targetReader.close();
}

2. With Guava

Next – let’s take a look at the Guava solution – using an intermediary byte array and String:

@Test
public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() 
  throws IOException {
    InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream();
    
    byte[] buffer = ByteStreams.toByteArray(initialStream);
    Reader targetReader = CharSource.wrap(new String(buffer)).openStream();

    targetReader.close();
}

Note that the Java solution is simpler than this approach.

3. With Commons IO

Finally – the solution using Apache Commons IO – also using an intermediary String:

@Test
public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect() 
  throws IOException {
    InputStream initialStream = IOUtils.toInputStream("With Commons IO");
    
    byte[] buffer = IOUtils.toByteArray(initialStream);
    Reader targetReader = new CharSequenceReader(new String(buffer));

    targetReader.close();
}

And there you have it – 3 quick ways to convert the input stream to a Java Reader.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Notify of
Samuel Kerrien
Guest
Samuel Kerrien

While it works, looks to me like the Guava and IoUtils solution will load all data into memory … beware of the evil OOME 😉 Better stick with the Java option in this case which is also more elegant …

Eugen Paraschiv
Guest

That’s definitely true – for small amounts of data, all of these will work fine, but for streaming through a large data load – copying it in memory isn’t the way to go. I covered working with large files here if you want to go more in-depth into it. Thanks for the feedback. Cheers,
Eugen.