Writing Files with PrintWriter

Saving Data Permanently to Files

Module 3 • Lesson 4 of 5

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."

Key Insight

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!

Writing to Console
System.out.println( "Hello!" ); System.out.print( "World" );
Writing to File
writer.println( "Hello!" ); writer.print( "World" );

2 Creating a PrintWriter

There are several ways to create a PrintWriter:

import java.io.File; import java.io.PrintWriter; import java.io.FileNotFoundException; public class WriteFile { public static void main(String[] args) { try { // Method 1: Using File object File myFile = new File("output.txt"); PrintWriter writer = new PrintWriter(myFile); // Method 2: Directly with filename PrintWriter writer2 = new PrintWriter("output.txt"); // Write to the file writer.println("Hello, file!"); // IMPORTANT: Close the writer! writer.close(); } catch (FileNotFoundException e) { System.out.println("Error creating file!"); } } }
File Creation

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

PrintWriter writer = new PrintWriter("output.txt"); // println - adds newline writer.println("Hello, file!"); // print - no newline writer.print("Writing some more text..."); writer.println(" And a new line!"); // printf - formatted output String name = "Ahmed"; int score = 95; writer.printf( "%s scored %d points%n", name, score ); writer.close();
📄 output.txt (Result)
Hello, file!
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!"

Understanding the Buffer
Your Code Writes:
writer.println("Hello")
Buffer (Memory):
"Hello\n"
File (Disk):
After close()/flush()
Common Mistake!

If you forget to call close(), your file might be empty or incomplete! The data is sitting in the buffer, waiting to be written.

💻
Java Program
writer.println()
📦
Buffer
Temporary storage
OS Kernel
System calls
💾
Disk
Permanent storage
Behind the Scenes

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:

import java.io.PrintWriter; import java.io.FileNotFoundException; public class GradeReport { public static void main(String[] args) { // Student data String[] names = {"Ahmed", "Sara", "Mohammed"}; int[] scores = {85, 92, 78}; try { PrintWriter writer = new PrintWriter("report.txt"); // Write header writer.println("=== Grade Report ==="); writer.println(); // Write each student for (int i = 0; i < names.length; i++) { writer.printf( "Student: %-10s Score: %d%n", names[i], scores[i] ); } // Calculate and write average double sum = 0; for (int score : scores) { sum += score; } double average = sum / scores.length; writer.println(); writer.printf( "Class Average: %.2f%n", average ); writer.println("===================="); // IMPORTANT: Close the writer! writer.close(); System.out.println("Report saved to report.txt"); } catch (FileNotFoundException e) { System.out.println("Error creating report file!"); } } }
📄 report.txt (Output File)
=== Grade Report ===

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:

import java.io.File; import java.io.PrintWriter; import java.io.FileNotFoundException; import java.util.Scanner; public class CopyAndModify { public static void main(String[] args) { try { // Open input file for reading Scanner reader = new Scanner( new File("input.txt") ); // Open output file for writing PrintWriter writer = new PrintWriter( "output.txt" ); int lineNum = 1; while (reader.hasNextLine()) { String line = reader.nextLine(); // Add line numbers to each line writer.printf( "%3d: %s%n", lineNum, line ); lineNum++; } // Close both! reader.close(); writer.close(); System.out.println("File processed successfully!"); } catch (FileNotFoundException e) { System.out.println( "Error: " + e.getMessage() ); } } }
Best Practice

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

Key Takeaways
  • 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!