InputStream to Reader in Java

An InputStreamReader is a bridge from byte streams to the character stream. It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or maybe given explicitly, or the platform's default charset may be accepted.

Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

In this tutorial, we will see how to convert InputStream to Reader.

1). Using Plain Java

InputStream inputStream = new ByteArrayInputStream("Hello World!!!!".getBytes()); Reader reader = new InputStreamReader(inputStream); reader.close();

2). Using Google's Guava

Google's Guava library has ByteSource and ByteStreams classes, using which we can convert InputStream to Reader.

Maven Dependency

<!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>30.0-jre</version> </dependency>

InputStream inputStream = ByteSource.wrap("Hello World!!!".getBytes()).openStream(); byte[] buffer = ByteStreams.toByteArray(inputStream); Reader reader = CharSource.wrap(new String(buffer)).openStream(); reader.close();

3). Using Commons IO

The Apache Common IO's IOUtils class we can convert InputStream to Reader.

Maven Dependency

<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>

InputStream inputStream = IOUtils.toInputStream("Hello World!!!"); byte[] buffer = IOUtils.toByteArray(inputStream); Reader reader = new CharSequenceReader(new String(buffer)); reader.close();

In this article, we have seen InputStream to Reader in Java.