InputStreamReader in Java

What is InputStreamReader?

InputStreamReader is a bridge between byte streams and character streams. It reads bytes from an input stream and decodes them into characters using a specified character encoding. This is especially useful when you need to read character data (text) from a byte-based stream like FileInputStream, Socket.getInputStream(), or System.in.

How Does InputStreamReader Work?

  • Without InputStreamReader: If you directly use InputStream classes like FileInputStream or System.in, you deal with raw bytes, which may not be suitable for reading text.
  • With InputStreamReader: It converts bytes into characters, allowing you to read text properly. It’s commonly used when reading text data from files or network streams where the underlying data is in bytes.

Constructors of InputStreamReader

InputStreamReader(InputStream in)
InputStreamReader(InputStream in, String charsetName) 
// in: InputStream object, charsetName: character encoding
  • InputStream in: The byte-based input stream (like FileInputStream, System.in, etc.).
  • charsetName: The character encoding to be used, such as "UTF-8" or "ISO-8859-1". If not specified, the platform's default encoding is used.

Key Methods of InputStreamReader

  • read(): Reads a single character from the input stream.
  • read(char[] cbuf, int offset, int length): Reads characters into a portion of a character array.
  • close(): Closes the reader and releases system resources.
Code Example

Explanation:

  • InputStreamReader is used to read characters from FileInputStream, converting bytes to characters using UTF-8 encoding.
  • isr.read() reads one character at a time from the file.
  • The character is printed to the console using System.out.print().

Explanation:

  • InputStreamReader converts bytes from System.in (which is an InputStream) into characters.
  • BufferedReader is used to read lines of text more efficiently.
  • This is a typical example of reading console input using InputStreamReader.