InputStreamReader: Converting Bytes to Characters
What you'll learn: How to use InputStreamReader to bridge byte streams and character streams by decoding bytes into characters using a specified charset.
The Bridge Between Worlds
Remember the byte-to-character impedance mismatch from the previous lesson? An InputStream deals with raw bytes, but when those bytes represent text, you need to interpret them as characters using a specific encoding (like UTF-8 or ISO-8859-1). That's exactly what InputStreamReader does—it wraps an InputStream and converts bytes to characters on the fly.
Think of InputStreamReader as a translator. The InputStream speaks "bytes," but your program wants to hear "characters." The InputStreamReader sits between them, decoding each byte sequence according to the charset you specify.
How It Works
You create an InputStreamReader by wrapping an existing InputStream:
InputStream in = new FileInputStream("data.txt");
Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
Now when you call read() on the reader, it:
- Reads one or more bytes from the underlying
InputStream - Decodes those bytes into a character using UTF-8
- Returns that character to you
You can specify the charset explicitly (recommended) or let it use the platform default (risky—different machines may behave differently).
When to Use It
Use InputStreamReader when you have a byte stream but need character-based operations. For example, wrapping System.in to read keyboard input as characters, or reading text from a network socket that delivers bytes.
Key Takeaway: InputStreamReader is the essential adapter that converts byte-oriented InputStream objects into character-oriented Reader objects, decoding bytes according to a specified charset.