InputStreamReader in Java

The InputStreamReader class in Java is an abstract class defined in java.io package. It is extended from Reader class and introduced in Java 1.1 version.

public class InputStreamReader
extends Reader

The InputStreamReader is a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset.

It has multiple constructors to take InputStream type object. Those constructors are,

  • public InputStreamReader(InputStream in):- It creates an InputStreamReader that uses the default charset.
  • public InputStreamReader(InputStream in, String charsetName) throws UnsupportedEncodingException:- Creates an InputStreamReader that uses the named charset. It throws UnsupportedEncodingException when the named charset is not supported.
  • public InputStreamReader(InputStream in, Charset cs):- Creates an InputStreamReader that uses the given charset.
  • public InputStreamReader(InputStream in, CharsetDecoder dec):- It creates an InputStreamReader that uses the given charset decoder.

Whereas an OutputStreamWriter is a bridge from character streams to byte streams. Characters written to it are encoded into bytes using a specified charset. It has several constructors to take OutputStream type object.

Java InputStreamReader Class Methods

Modifier and TypeMethodDescription
public intread()It reads a single character.
public intread(char cbuf[], int offset, int length)It reads characters into a portion of an array.
public booleanready()It tells whether this stream is ready to be read.
public voidclose()It closes the connection.
StringgetEncoding()It returns the name of the character encoding being used by this stream.

An InputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read from the underlying byte stream.

Subclasses:- It has only one subclass FileReader which is used to read data from the file.

To connect BufferedReader object with Keyboard,

  • pass System.in as an argument to InputStreamReader object creation
  • pass InputStreamReader object as an argument to BufferedReader object creation

Syntax of BufferedReader to connect to keyboard is,

// create BufferedReader and InputStreamReader object
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

Or,
// it can be written in one line as
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *