Writing Text to System.out with OutputStreamWriter
You'll learn how to wrap System.out in an OutputStreamWriter to control exactly how characters are encoded when writing to the console.
The Problem with Direct System.out Usage
When you use System.out.print() or println(), Java converts your characters to bytes using the platform's default encoding. You have no control over this process. If your application runs on different systems with different default encodings, your output might look different—or break entirely with special characters.
OutputStreamWriter to the Rescue
System.out is a PrintStream, which is ultimately a byte-oriented stream. By wrapping it in an OutputStreamWriter, you create a bridge that explicitly controls the character-to-byte conversion. You specify the encoding, making your output predictable across platforms.
How It Works
OutputStreamWriter writer = new OutputStreamWriter(System.out, StandardCharsets.UTF_8);
writer.write("Hello, 世界!\n");
writer.flush(); // Important: force output to appear immediately
This creates a Writer that sends characters to the console using UTF-8 encoding, regardless of your platform's default. The flush() call is critical because OutputStreamWriter buffers data—without it, your text might sit in memory instead of appearing on screen.
Think of it like this: System.out is a pipe that carries water (bytes). OutputStreamWriter is a translator that converts your instructions (characters) into the right "water pressure" (bytes with specified encoding) before sending them through the pipe.
Why This Matters
When writing non-ASCII characters (accented letters, emojis, Chinese characters), explicit encoding prevents garbled output and ensures your application behaves identically on Windows, Linux, and macOS.
Key Takeaway: Wrap System.out in OutputStreamWriter with an explicit Charset to guarantee consistent character encoding when writing to the console, and always flush() to ensure immediate output.