Concept Explanation
If the File class is the clerk, FileWriter is the Pen. Just having a piece of paper (a File object) isn't enough; you need a tool to press ink onto it.
Syntax or Core Structure
1. Creating a File
We use createNewFile() which returns true only if the file didn't exist before.
File myFile = new File("notes.txt");
if (myFile.createNewFile()) {
System.out.println("Success! New file made.");
}
2. Writing to a File
We use FileWriter. Important: You must close() the writer, or the ink won't dry (data won't be saved!).
try (FileWriter writer = new FileWriter("notes.txt")) {
writer.write("Hello Java Files!
");
writer.write("Writing is easy.");
} catch (IOException e) {
System.out.println("Failed to write!");
}
Real-World Example: User Activity Log
Imagine an app that records every time a user logs in.
public void logLogin(String username) {
try (FileWriter fw = new FileWriter("log.txt", true)) { // 'true' means APPEND
fw.write("User " + username + " logged in at " + new java.util.Date() + "
");
} catch (IOException e) {
e.printStackTrace();
}
}
Best Practices
- Use Append Mode: Use
new FileWriter("file.txt", true)if you want to add to a file instead of overwriting it. - Try-with-resources: Always use it to ensure the file is closed automatically.
Practice Exercises
- The Diary: Build a program that asks the user for 3 lines of text and saves them to "diary.txt".
- The Appender: Write a method that adds a timestamp to a file every time it's called without deleting old entries.
- The Override: What happens if you run
new FileWriter("data.txt")(without thetrueflag) on a file that already has content?