PrintWriter Class in Java: Formatted Text Output
PrintWriter gives text output the same convenient methods as System.out: print(), println() and printf(). It writes to files, sockets, strings or any other Writer, which makes it a natural choice for reports and formatted text.
This tutorial covers its constructors and methods, and two examples, including how automatic flushing works.
1. What Is PrintWriter in Java?
PrintWriter extends Writer and prints values of any type as text. It was added in Java 1.1. Like PrintStream, its methods never throw IOException; check checkError() instead.
2. PrintWriter Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of PrintWriter
| Constructor | Description |
|---|---|
PrintWriter(Writer out) / PrintWriter(Writer out, boolean autoFlush) | Prints to another writer. |
PrintWriter(OutputStream out, boolean autoFlush, Charset charset) | Prints to a byte stream with a charset (Java 10). |
PrintWriter(String fileName) / PrintWriter(File file) | Prints to a file (Java 5). |
PrintWriter(File file, Charset charset) | Prints to a file with a charset (Java 10). |
4. Commonly Used Methods
| Method | Description |
|---|---|
print(x) / println(x) | Prints any value; println adds the platform line separator. |
printf(...) / format(...) | Formatted output (Java 5). |
append(CharSequence csq) | Adds text and returns the writer (Java 5). |
boolean checkError() | Flushes and reports whether an error has occurred. |
flush() / close() | Pushes out buffered text; closes the destination. |
5. Example: Printing a Salary Slip
A payroll system prints salary slips with aligned columns.
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
public class SalarySlip {
public static void main(String[] args) throws IOException {
Path slip = Files.createTempFile("slip", ".txt");
double basic = 45000, hra = 18000, tax = 6250.5;
try (PrintWriter out = new PrintWriter(slip.toFile(), StandardCharsets.UTF_8)) { // Java 10
out.println("SALARY SLIP - NOVEMBER 2026");
out.printf(Locale.ROOT, "%-10s %10.2f%n", "Basic", basic);
out.printf(Locale.ROOT, "%-10s %10.2f%n", "HRA", hra);
out.printf(Locale.ROOT, "%-10s %10.2f%n", "Tax", -tax);
out.printf(Locale.ROOT, "%-10s %10.2f%n", "Net pay", basic + hra - tax);
System.out.println("Errors while writing: " + out.checkError());
}
System.out.print(Files.readString(slip));
Files.delete(slip);
}
}
Errors while writing: false SALARY SLIP - NOVEMBER 2026 Basic 45000.00 HRA 18000.00 Tax -6250.50 Net pay 56749.50
How the code works
new PrintWriter(file, StandardCharsets.UTF_8)(Java 10) opens the file with an explicit charset.%-10sleft-aligns the label, and%10.2fright-aligns the amount with two decimals.Locale.ROOTkeeps the decimal point as.on every computer.checkError()returnsfalse, so every line was written.
6. Example: How Auto-Flush Works
A server writes status messages through a buffered writer. This example shows when text actually reaches the destination.
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
public class AutoFlushDemo {
public static void main(String[] args) {
StringWriter manual = new StringWriter();
PrintWriter noFlush = new PrintWriter(new BufferedWriter(manual)); // autoFlush = false
noFlush.println("Server started");
System.out.println("Without auto-flush: \"" + manual.toString().strip() + "\"");
StringWriter auto = new StringWriter();
PrintWriter withFlush = new PrintWriter(new BufferedWriter(auto), true); // autoFlush = true
withFlush.println("Server started");
System.out.println("With auto-flush: \"" + auto.toString().strip() + "\"");
noFlush.close();
withFlush.close();
System.out.println("After close: \"" + manual.toString().strip() + "\"");
}
}
Without auto-flush: "" With auto-flush: "Server started" After close: "Server started"
How the code works
- Without auto-flush,
println()leaves the text in theBufferedWriter, so theStringWriteris still empty. - With
autoFlush = true,println()flushes immediately. - Closing the first writer flushes it too, so its text finally appears.
- Unlike
PrintStream,PrintWriterflushes only onprintln,printfandformat, not whenever a newline character is printed.
7. Common Mistakes and Best Practices
- Never checking for errors. Failures are silent; call
checkError()for important output. - Forgetting to close or flush. Buffered text is lost.
- Expecting
print("...\n")to auto-flush. Onlyprintln,printfandformatdo. - Using locale-dependent formats in data files. Pass
Locale.ROOT.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.1 | PrintWriter introduced. |
| Java 5 | printf(), format(), append() and file constructors. |
| Java 10 | Constructors with a Charset. |
| Java 25 | No API changes. |
9. Summary
PrintWriterprints formatted text to any writer, stream or file.- Its methods never throw
IOException; usecheckError(). - Auto-flush happens only on
println,printfandformat. - Pass a
Charsetand close it with try-with-resources.