How to Use PrintWriter in Java: Simple Guide with Examples
Use
PrintWriter in Java to write formatted text output to files, streams, or other destinations. Create a PrintWriter object by passing a file or output stream, then use methods like print() or println() to write text. Always close the writer to save and release resources.Syntax
The basic syntax to create a PrintWriter is:
PrintWriter writer = new PrintWriter(File file);- writes to a file.PrintWriter writer = new PrintWriter(OutputStream out);- writes to an output stream.- Use
writer.print()orwriter.println()to write text. - Call
writer.close()to save and free resources.
java
PrintWriter writer = new PrintWriter("output.txt"); writer.println("Hello, world!"); writer.close();
Example
This example shows how to write text lines to a file using PrintWriter. It writes two lines and closes the writer to save the file.
java
import java.io.PrintWriter; import java.io.FileNotFoundException; public class PrintWriterExample { public static void main(String[] args) { try (PrintWriter writer = new PrintWriter("example.txt")) { writer.println("First line of text."); writer.println("Second line of text."); } catch (FileNotFoundException e) { System.out.println("File not found or cannot be created."); } } }
Common Pitfalls
Common mistakes when using PrintWriter include:
- Not closing the writer, which can cause data not to be saved.
- Ignoring exceptions like
FileNotFoundExceptionwhen the file cannot be created. - Using
PrintWriterwithout buffering for large files, which can be inefficient.
Always use try-with-resources or close the writer in a finally block.
java
/* Wrong way: Not closing the writer */ PrintWriter writer = new PrintWriter("file.txt"); writer.println("Hello"); // writer.close() missing - data may not be saved /* Right way: Using try-with-resources */ try (PrintWriter writer2 = new PrintWriter("file.txt")) { writer2.println("Hello"); }
Quick Reference
| Method | Description |
|---|---|
| PrintWriter(File file) | Creates a writer to write to the specified file. |
| print(String s) | Writes text without a newline. |
| println(String s) | Writes text followed by a newline. |
| close() | Closes the writer and flushes data. |
| flush() | Flushes the writer without closing. |
Key Takeaways
Create a PrintWriter by passing a file or output stream to write text output.
Use print() or println() methods to write text lines.
Always close the PrintWriter to ensure data is saved and resources are freed.
Handle exceptions like FileNotFoundException when creating the writer.
Use try-with-resources for safe and clean resource management.