00:00

PrintWriter Class in Java: Formatted Text Output

Last updated:

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

PrintWriter class hierarchyPrintWriter extends the abstract class Writer, which extends Object, and implements Appendable, Closeable, Flushable and AutoCloseable. When automatic flushing is enabled, it flushes on println, printf and format.ObjectextendsWriterabstract classextendsPrintWriterprints formatted textAppendableCloseableFlushableAutoCloseableimplementsAuto-flush happens onprintln()printf()format()

Swipe sideways to see the whole diagram.

3. Constructors of PrintWriter

ConstructorDescription
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

MethodDescription
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.

SalarySlip.java
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);
    }
}
Output
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

  1. new PrintWriter(file, StandardCharsets.UTF_8) (Java 10) opens the file with an explicit charset.
  2. %-10s left-aligns the label, and %10.2f right-aligns the amount with two decimals.
  3. Locale.ROOT keeps the decimal point as . on every computer.
  4. checkError() returns false, 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.

AutoFlushDemo.java
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() + "\"");
    }
}
Output
Without auto-flush: ""
With auto-flush:    "Server started"
After close:        "Server started"

How the code works

  1. Without auto-flush, println() leaves the text in the BufferedWriter, so the StringWriter is still empty.
  2. With autoFlush = true, println() flushes immediately.
  3. Closing the first writer flushes it too, so its text finally appears.
  4. Unlike PrintStream, PrintWriter flushes only on println, printf and format, 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. Only println, printf and format do.
  • Using locale-dependent formats in data files. Pass Locale.ROOT.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.1PrintWriter introduced.
Java 5printf(), format(), append() and file constructors.
Java 10Constructors with a Charset.
Java 25No API changes.

9. Summary

  • PrintWriter prints formatted text to any writer, stream or file.
  • Its methods never throw IOException; use checkError().
  • Auto-flush happens only on println, printf and format.
  • Pass a Charset and close it with try-with-resources.

Related Tutorials

10. Official Java Documentation References