Specifying Charset in Bridge Constructors
You'll learn how to explicitly control character encoding when creating InputStreamReader and OutputStreamWriter instances.
The Problem: Default Encoding Isn't Always Right
When you create an InputStreamReader or OutputStreamWriter without specifying encoding, Java uses your platform's default charset. This works fine on your machine but can cause data corruption when files move between systems with different defaults (Windows-1252 vs UTF-8, for example).
Explicit Charset Control
Both bridge classes offer constructors that accept a Charset object or charset name string:
InputStreamReader constructors:
InputStreamReader(InputStream in, Charset cs)InputStreamReader(InputStream in, String charsetName)
OutputStreamWriter constructors:
OutputStreamWriter(OutputStream out, Charset cs)OutputStreamWriter(OutputStream out, String charsetName)
Why This Matters
Think of charset specification like tuning a radio to the right frequency. Without it, you might hear static (garbled characters). By explicitly setting the charset, you guarantee that:
- UTF-8 encoded bytes decode as UTF-8 characters
- Your application behaves identically across Windows, Mac, and Linux
- International characters (émojis, 中文, العربية) display correctly
Using Standard Charsets
Java provides StandardCharsets constants for common encodings:
new InputStreamReader(fileInputStream, StandardCharsets.UTF_8)
new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8)
Or using string names:
new InputStreamReader(fileInputStream, "UTF-8")
new OutputStreamWriter(fileOutputStream, "ISO-8859-1")
Key Takeaway: Always specify the charset explicitly when creating InputStreamReader or OutputStreamWriter to ensure predictable, portable character encoding behavior across different platforms and avoid silent data corruption.