1 PrintWriter: Your Magic Pen
The teacher took out a magic pen called PrintWriter.
"This," they said, "lets us write text into a file, just like System.out.print writes text to the screen."
Just as we use System.out.println() to print to the console, we use PrintWriter to "print" to a file. The methods are almost identical!
2 Creating a PrintWriter
There are several ways to create a PrintWriter:
If the file doesn't exist, PrintWriter will create it. If it does exist, PrintWriter will overwrite it (erasing old content)!
3 PrintWriter Methods
| Method | Description |
|---|---|
print(data) |
Writes data without a newline at the end |
println(data) |
Writes data followed by a newline |
printf(format, args) |
Writes formatted output (like C's printf) |
flush() |
Forces buffered data to be written to file |
close() |
Flushes and closes the writer |
Example: Using Different Write Methods
Writing some more text... And a new line!
Ahmed scored 95 points
4 Why Must We Close or Flush?
The teacher shared this secret: "When you write data to a file, Java might keep some of that data in a temporary area called a buffer. This makes writing more efficient."
"But if you never say 'write everything to the file now' (by closing or flushing), the data could stay in that buffer and never appear in the actual file!"
If you forget to call close(), your file might be empty or incomplete! The data is sitting in the buffer, waiting to be written.
When a Java program wants to write data to the hard disk, it eventually calls system calls provided by the operating system. Java's I/O classes talk to the JVM, which invokes the OS's file I/O system calls (like write() on Linux or WriteFile() on Windows). These system calls pass data to the OS kernel, which interacts with the file system and disk driver.
Note: The deep details will be covered in Operating Systems course.
5 Complete Example: Student Grade Report
Let's write a program that creates a grade report file:
Student: Ahmed Score: 85
Student: Sara Score: 92
Student: Mohammed Score: 78
Class Average: 85.00
====================
6 Reading and Writing Together
Often, you'll need to read from one file and write to another:
Always close your readers and writers when done. A good pattern is to close them in the reverse order of opening (close writer first, then reader).
7 Summary
- ✓ PrintWriter writes text to files like System.out writes to console.
- ✓ Use print(), println(), and printf() to write data.
- ✓ Data is buffered - stored temporarily before writing to disk.
- ✓ Always close() the writer to ensure data is saved!
- ✓ PrintWriter creates new files or overwrites existing ones.
And so, the student learned:
- Files store data even when programs stop running
- The File class lets us explore file properties
- Scanner reads from files like it reads from keyboard
- PrintWriter writes to files like System.out writes to screen
- Always close your writers to save data correctly!
End of the Tale!