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

Combining PrintWriter with Other Streams

Chain PrintWriter with OutputStreamWriter and other streams for flexible, formatted output pipelines.

Combining PrintWriter with Other Streams

You'll learn how to chain PrintWriter with OutputStreamWriter and other streams to create flexible, formatted output pipelines.

The Power of Stream Chaining

PrintWriter doesn't have to write directly to files—it can wrap any Writer or OutputStream. This lets you build pipelines that convert bytes to characters (encoding), add buffering, and format output all in one chain.

The most common pattern is: OutputStream → OutputStreamWriter (encoding) → PrintWriter (formatting)

This gives you full control: you choose the encoding, add buffering where needed, and get PrintWriter's convenient printf and println methods at the end.

Building a Stream Pipeline

try (FileOutputStream fos = new FileOutputStream("output.txt");
     OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
     PrintWriter writer = new PrintWriter(osw)) {
    
    writer.println("This text is UTF-8 encoded");
    writer.printf("Number: %d%n", 42);
} catch (IOException e) {
    e.printStackTrace();
}

Here you're chaining three layers:

  1. FileOutputStream writes raw bytes
  2. OutputStreamWriter converts characters to UTF-8 bytes
  3. PrintWriter provides formatted output methods

Why Chain Instead of Direct File Access?

When you create PrintWriter with just a filename, Java uses the platform's default encoding—dangerous for portability. Chaining with OutputStreamWriter lets you explicitly choose UTF-8 or any other charset.

You can also insert buffering:

PrintWriter writer = new PrintWriter(
    new BufferedWriter(
        new OutputStreamWriter(fos, StandardCharsets.UTF_8)
    )
);

Key Takeaway: Chain PrintWriter with OutputStreamWriter and other streams to control encoding, add buffering, and combine formatted output with flexible byte/character conversion—giving you precise control over how text becomes bytes on disk or network.