Java
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.
Exercise 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");.
Show example solution
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");
}
}
Test yourself
-
Match the PrintWriter methods
- println()
- Writes with a line separator
- printf()
- Performs formatted writing
- print()
- Writes without a line separator
- close()
- Closes the resource
-
Which PrintWriter call guarantees UTF-8?
- new PrintWriter("a.txt")
- new PrintWriter("a.txt", true)
- new PrintWriter("a.txt", "UTF-8")
- new PrintWriter()
Show answer
new PrintWriter("a.txt", "UTF-8") — Passing "UTF-8" as the second parameter guarantees the encoding.
-
Closing the PrintWriter
PrintWriter pw = new PrintWriter("a.txt", "UTF-8");
pw.println("Hello");
pw.____();
Show answer
PrintWriter pw = new PrintWriter("a.txt", "UTF-8");
pw.println("Hello");
pw.close();
Next lesson: try-with-resources