CodeBlanks Logo Icon CodeBlanks

PrintWriter

Learn formatted writing with PrintWriter.

Formatted writing with PrintWriter

PrintWriter provides formatted writing like System.out. Open it with PrintWriter pw = new PrintWriter("a.txt");; use pw.println("Hello"), pw.printf("%d", 42) and pw.print(...) methods. println also appends a line separator.

PrintWriter has an autoFlush feature: you can pass an encoding like new PrintWriter("a.txt", "UTF-8"). It is more convenient than FileWriter but still requires close().

PrintWriter encoding

If you open PrintWriter without an encoding, the system encoding is used; Turkish characters may vary across systems. With new PrintWriter("a.txt", "UTF-8") you always guarantee UTF-8 output.

The second parameter is a String holding the charset name. A wrong encoding name throws UnsupportedEncodingException. The StandardCharsets.UTF_8 constant is also a safe choice.

Practice Write formatted output with PrintWriter

Import java.io.PrintWriter and java.io.IOException. Add throws IOException to main. Create a PrintWriter pw = new PrintWriter("num.txt", "UTF-8");, write a header with pw.println("Header");, write a formatted number with pw.printf("Number: %d", 42);. Close with pw.close();. Then print System.out.println("Done");.

Starter code

Main.java
import java.io.PrintWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        // Write header and formatted number with PrintWriter in UTF-8

        // Print Done

    }
}

Sample solution

Main.java
import java.io.PrintWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        PrintWriter pw = new PrintWriter("num.txt", "UTF-8");
        pw.println("Header");
        pw.printf("Number: %d", 42);
        pw.close();
        System.out.println("Done");
    }
}

Expected output

Done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the PrintWriter methods

Term Meaning
println() Writes with a line separator
printf() Performs formatted writing
print() Writes without a line separator
close() Closes the resource

2 Which PrintWriter call guarantees UTF-8?

  • new PrintWriter("a.txt")
  • new PrintWriter("a.txt", true)
  • new PrintWriter("a.txt", "UTF-8") Correct answer
  • new PrintWriter()

Explanation: Passing "UTF-8" as the second parameter guarantees the encoding.

3 Closing the PrintWriter

Question
PrintWriter pw = new PrintWriter("a.txt", "UTF-8");
pw.println("Hello");
pw.____();
Answer
PrintWriter pw = new PrintWriter("a.txt", "UTF-8");
pw.println("Hello");
pw.close();

Explanation: close releases the resource and flushes data to disk.

All lessons in Intermediate