PrintStream and PrintWriter in Java

Naveen AnamaneniUpdated · 4 min read
easyJava 25javaiooutput

PrintStream and PrintWriter are output streams that add the convenient methods print, println and printf for writing values as readable text. You already use one every day: System.out is a PrintStream. PrintStream is a byte stream, and PrintWriter is the character-stream version that is preferred for writing text to files. Unlike other streams, neither one throws IOException; they record errors internally instead. In this lesson, you will learn both classes and how to write formatted text to files.

Declaration

Declaration
public class PrintStream extends FilterOutputStream
        implements Appendable, Closeable
public class PrintWriter extends Writer

Methods

MethodDescription
print(x)It is used to write any value as text.
println(x)It writes the value followed by a line separator.
printf(format, args...) / format(...)It writes formatted text, like String.format.
flush()It pushes buffered text to the destination.
checkError()It flushes and returns true if an error has happened.

PrintStream vs PrintWriter

PrintStreamPrintWriter
FamilyByte stream (OutputStream)Character stream (Writer)
Best known asSystem.out, System.errWriting text files and reports
Can wrapOutputStreamWriter or OutputStream
Autoflush on printlnOptionalOptional (only println, printf, format)
Throws IOExceptionNo; use checkError()No; use checkError()

Example: Writing a Report with PrintWriter

Let's see an example that writes a formatted marks report to a file.

Report.java▶ Try it
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
 
public class Report {
    record Student(String name, int marks) { }
 
    public static void main(String[] args) throws IOException {
        Student[] students = {
            new Student("Navika", 91), new Student("Srihitha", 78),
            new Student("Advitha", 85)};
 
        try (PrintWriter out = new PrintWriter(
                new FileWriter("report.txt", StandardCharsets.UTF_8))) {
            out.println("MARKS REPORT");
            out.printf("%-10s %5s%n", "Name", "Marks");
            for (Student s : students) {
                out.printf("%-10s %5d%n", s.name(), s.marks());
            }
            out.printf("Average: %.2f%n", (91 + 78 + 85) / 3.0);
        }
 
        System.out.print(Files.readString(Path.of("report.txt")));
    }
}
Output
MARKS REPORT
Name       Marks
Navika        91
Srihitha      78
Advitha       85
Average: 84.67

Explanation: PrintWriter wraps a FileWriter, adding println and printf. %-10s prints a name left-aligned in 10 columns, %5d a number right-aligned in 5, and %.2f two decimal places. %n is the line separator. The file is then read back and printed.

Example: Errors Don't Throw

CheckError.java▶ Try it
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
 
public class CheckError {
    public static void main(String[] args) {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(buffer);
        ps.println("Hello, Srihitha");
        System.out.println("Error so far? " + ps.checkError());
 
        ps.close();
        ps.println("written after close");
        System.out.println("Error after close? " + ps.checkError());
        System.out.print("Captured: " + buffer);
    }
}
Output
Error so far? false
Error after close? true
Captured: Hello, Srihitha

Explanation: Writing after close() fails, but println doesn't throw. Instead, the stream sets an error flag that checkError() reports. The text written before closing was captured in the in-memory buffer.

Common Mistakes

Assuming writes succeeded because no exception was thrown. Check checkError().

Using \n in printf when the file must match the system's line endings. Use %n.

Forgetting to close the PrintWriter. Buffered text may be lost.

Practice

  1. Easy: Write a multiplication table from 1 to 10 to table.txt with printf, lining up the columns.
  2. Harder: Redirect System.out to a file with System.setOut(new PrintStream(...)), print a few lines, then restore the original System.out.

Quick check: PrintStream and PrintWriter

4 questions
1What type is System.out?
2Do print methods throw IOException?
3Which format specifier prints a line separator?
4Which class is preferred for writing text files?

Key Takeaways

Was this tutorial helpful?

Lesson 346 of 482