Creating PrintWriter Instances
You'll learn how to create PrintWriter objects from various sources including files, byte streams, and other character streams, with optional auto-flush control.
The Core Idea
PrintWriter is your go-to class for writing formatted text output. Unlike basic Writer classes, you can create PrintWriter instances in multiple flexible ways depending on your data source and whether you want automatic flushing after every line-based write operation.
Construction Options
From a File Path or File Object
The simplest approach—pass a file path as a String or a File object:
PrintWriter writer1 = new PrintWriter("output.txt");
PrintWriter writer2 = new PrintWriter(new File("data.txt"));
These constructors handle character encoding using the platform default.
From an OutputStream
Wrap any byte stream, like FileOutputStream:
FileOutputStream fos = new FileOutputStream("output.txt");
PrintWriter writer = new PrintWriter(fos);
From Another Writer
Chain with other character streams like BufferedWriter:
FileWriter fw = new FileWriter("output.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter writer = new PrintWriter(bw);
The Auto-Flush Option
Add a boolean second parameter to enable auto-flush, which flushes the buffer after every println, printf, or format call:
FileOutputStream fos = new FileOutputStream("output.txt");
PrintWriter writer = new PrintWriter(fos, true); // auto-flush enabled
Note: Auto-flush only triggers on line-oriented methods, not print().
Try-With-Resources
Always use try-with-resources to ensure proper closing:
try (PrintWriter writer = new PrintWriter("output.txt")) {
// write operations here
}
Key Takeaway: PrintWriter offers flexible construction from files, streams, or writers, with optional auto-flush for immediate output visibility—choose the constructor that matches your input source and buffering needs.