Writing to Files with PrintWriter
You'll learn how to write formatted text directly to files using PrintWriter with proper character encoding and resource management.
Now that you understand PrintWriter's methods, let's see how to use it to write actual files—the most common real-world use case.
Creating PrintWriter for File Output
You can create a PrintWriter that writes directly to a file by passing a file path string or File object to its constructor. Internally, Java creates the necessary byte stream and character conversion layers for you:
try (PrintWriter writer = new PrintWriter("output.txt")) {
writer.println("Hello, file!");
writer.printf("Number: %d%n", 42);
} catch (FileNotFoundException e) {
System.err.println("Could not create file: " + e.getMessage());
}
Specifying Character Encoding
To control how characters are converted to bytes, pass a Charset along with the file path:
try (PrintWriter writer = new PrintWriter("output.txt", StandardCharsets.UTF_8)) {
writer.println("Unicode: こんにちは");
writer.printf("Value: %.2f%n", 3.14159);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
This ensures your file uses UTF-8 encoding rather than the platform's default encoding.
Why Try-With-Resources Is Essential
PrintWriter buffers output internally. If you don't close it properly, buffered data may never reach the file. Try-with-resources guarantees the writer closes (and flushes) even if exceptions occur during writing.
Practical Example
try (PrintWriter writer = new PrintWriter("report.txt", StandardCharsets.UTF_8)) {
writer.println("Sales Report");
writer.println("=============");
writer.printf("Total: $%.2f%n", 1234.56);
// Data is automatically flushed and file closed
}
Key Takeaway: Always use try-with-resources when creating PrintWriter for file output, and specify StandardCharsets.UTF_8 to ensure consistent character encoding across platforms.