Specifying Charset in Readers and Writers
You'll learn how to explicitly control character encoding by passing Charset objects to InputStreamReader and OutputStreamWriter.
Why It Matters
You've learned that bridge classes convert between byte streams and character streams, and that Charset objects represent character encodings. Now comes the critical step: wiring them together. When you create an InputStreamReader or OutputStreamWriter, you can pass a Charset to tell Java exactly how to decode bytes into characters (or encode characters into bytes).
Specifying Charset in InputStreamReader
Instead of relying on the platform default encoding (which varies between systems), pass a Charset as the second constructor argument:
InputStream in = new FileInputStream("data.txt");
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
This guarantees that data.txt will be read as UTF-8, regardless of what computer runs your code.
Specifying Charset in OutputStreamWriter
The same principle applies when writing:
OutputStream out = new FileOutputStream("output.txt");
OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
writer.write("Hello, 世界!");
writer.close();
Now output.txt will contain UTF-8 encoded bytes, ensuring the Chinese characters are preserved correctly.
Why This Is Essential
Think of Charset as the instruction manual for translating between bytes and characters. Without it, Java guesses based on your operating system—Windows might use Windows-1252, Linux might use UTF-8. By specifying the charset explicitly, you make your code portable and predictable.
Key Takeaway: Always pass a Charset (like StandardCharsets.UTF_8) to InputStreamReader and OutputStreamWriter constructors to explicitly control how bytes are converted to characters and vice versa, avoiding platform-dependent encoding issues.