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.
InputStream classes like FileInputStream or System.in, you deal with raw bytes, which may not be suitable for reading text.Constructors of InputStreamReader
InputStreamReader(InputStream in)
InputStreamReader(InputStream in, String charsetName)
// in: InputStream object, charsetName: character encoding
FileInputStream, System.in, etc.).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.import java.io.InputStreamReader;import java.io.FileInputStream;import java.io.IOException;public class InputStreamReaderExample { public static void main(String[] args) { try (InputStreamReader isr = new InputStreamReader(new FileInputStream("example.txt"), "UTF-8")) { int data; while ((data = isr.read()) != -1) { // Reads one character at a time System.out.print((char) data); // Convert the integer to a character and print } } catch (IOException e) { e.printStackTrace(); } }}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.System.out.print().xxxxxxxxxximport java.io.InputStreamReader;import java.io.BufferedReader;import java.io.IOException;public class ConsoleInputExample { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("Enter your name: "); String name = br.readLine(); // Reading input from the console System.out.println("Hello, " + name + "!"); } catch (IOException e) { e.printStackTrace(); } }}Explanation:
InputStreamReader converts bytes from System.in (which is an InputStream) into characters.BufferedReader is used to read lines of text more efficiently.InputStreamReader.