Course contentsShow
← Java
Lesson 1989 of 2,87040. File I/O: Character StreamsFree lesson

OutputStreamWriter: Converting Characters to Bytes

Using OutputStreamWriter to wrap an OutputStream and encode characters into bytes using a charset.

OutputStreamWriter: Converting Characters to Bytes

You'll learn how to write character data to byte-based output streams by wrapping them with OutputStreamWriter and specifying character encoding.

The Core Idea

OutputStreamWriter is the output counterpart to InputStreamWriter. While you've just learned how to read bytes and convert them to characters, now you need to do the reverse: take characters from your Java program and write them as bytes to a file, network socket, or any OutputStream.

Think of OutputStreamWriter as a translator at a publishing house. Your manuscript (Java characters) needs to be printed (written as bytes), but the printing press only understands a specific format (a charset like UTF-8). The translator converts your text into that format before sending it to the press.

Why You Need It

Writer deals in characters, but underlying devices (files, network streams) only understand bytes. OutputStreamWriter bridges this gap by encoding your characters into bytes using a specified charset.

Basic Usage

Wrap any OutputStream with an OutputStreamWriter and specify the encoding:

OutputStream out = new FileOutputStream("output.txt");
Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);

writer.write("Hello, 世界!"); // Characters encoded to UTF-8 bytes
writer.flush();
writer.close();

Without specifying a charset, OutputStreamWriter uses your platform's default encoding—which you learned is risky. Always specify explicitly.

How It Works

When you call writer.write(), the OutputStreamWriter encodes each character according to the charset rules, then writes the resulting bytes to the underlying OutputStream. Multi-byte characters (like "世") become multiple bytes in UTF-8.

Key Takeaway: OutputStreamWriter wraps an OutputStream to convert characters into bytes using a specified charset, enabling you to write text data to byte-oriented destinations with explicit encoding control.