🔁 Classes that Convert Between Byte and Character Streams
🔹 1. InputStreamReader
- Converts:
InputStream→Reader - Direction: Byte → Character
- Use case: Reading a byte stream (e.g., from a file or network) as text.
✅ Example:
InputStream is = new FileInputStream("input.txt");
Reader reader = new InputStreamReader(is, "UTF-8");
- Wraps an
InputStream - Decodes bytes into characters using a charset (e.g., UTF-8)
🔹 2. OutputStreamWriter
- Converts:
Writer→OutputStream - Direction: Character → Byte
- Use case: Writing text to an
OutputStream, like saving to a file or sending over a network.
✅ Example:
OutputStream os = new FileOutputStream("output.txt");
Writer writer = new OutputStreamWriter(os, "UTF-8");
- Encodes characters into bytes using a charset
🌐 Why is this important?
Because:
- Streams are binary, but most data we handle is text.
- You need to decode incoming bytes to characters when reading text.
- You need to encode characters to bytes when writing text.
🧵 TL;DR
| Class | Converts | Direction | Charset-aware? | Use Case |
|---|---|---|---|---|
InputStreamReader | InputStream → Reader | Byte → Char | ✅ Yes | Read bytes as text |
OutputStreamWriter | Writer → OutputStream | Char → Byte | ✅ Yes | Write text as bytes |