Course contentsShow
← Java
Lesson 1993 of 2,87040. File I/O: Character StreamsFree lesson

Reading Text from System.in with InputStreamReader

Wrapping System.in in InputStreamReader to read console input as character data.

Reading Text from System.in with InputStreamReader

You'll learn how to properly read console input as character data by wrapping System.in with an InputStreamReader.

The Console Input Challenge

System.in is an InputStream — it only provides raw bytes, not characters. When you want to read text typed by a user at the console, you need to convert those bytes into proper characters using the correct encoding. This is exactly what InputStreamReader does.

How It Works

Think of System.in as a pipe delivering raw water (bytes), and InputStreamReader as a filter that turns it into clean drinking water (characters). You wrap System.in inside an InputStreamReader to bridge from byte streams to character streams:

InputStreamReader reader = new InputStreamReader(System.in);

This creates a character stream that reads from the console. By default, it uses your platform's default encoding, but you should always specify an encoding explicitly for predictable behavior:

InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);

Reading Console Input

Once wrapped, you can read characters from the console. Typically, you'll wrap this further in a BufferedReader to use convenient methods like readLine():

InputStreamReader isr = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader console = new BufferedReader(isr);

String line = console.readLine();  // Read a full line of user input

Unlike file streams, don't close System.in — closing it would prevent any further console input for the entire program.

Why This Matters

Without InputStreamReader, you'd be stuck working with raw bytes from System.in, making it painful to handle text properly across different languages and character sets.

Key Takeaway: Wrap System.in with InputStreamReader (specifying StandardCharsets.UTF_8) to read console input as character data instead of raw bytes.