Jan 24, 2026
## Chapter 16: File Handling (The "Diary" of Your Program)
Up until now, every time we ran our program, the data would disappear as soon as the program stopped. In the real world, we need to save things. Whether it's a high score in a game or a list of customers, we use **Files**.
I tell my students: **File handling is like writing in a diary.** You write it down today, and you can read it tomorrow.
### 1. Writing to a File
**Example 1: Saving a Secret (Basic)**
```java
import java.nio.file.Files;
import java.nio.file.Path;
try {
String message = "Java is fun!";
Files.writeString(Path.of("secret.txt"), message);
System.out.println("Saved!");
} catch (IOException e) {
System.out.println("Error saving!");
}
```
### 2. Common Student Mistake: The "Where is my file?" Problem
**Example 2: The Path Trap**
```java
// MISTAKE: Using a path that doesn't exist or forgetting folders
Files.readString(Path.of("C:/Users/me/Documents/missing_folder/test.txt"));
```
*Teacher's Note:* Students often hardcode paths like `C:/Users/...`. This is a bad habit! If you send your code to a friend, it won't work on their computer. Always keep files in your project folder and just use the filename like `"data.txt"`.
### 3. Reading a File
**Example 3: Reading Line-by-Line (Memory Efficient)**
```java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
try {
List<String> lines = Files.readAllLines(Path.of("myFile.txt"));
for (String line : lines) {
System.out.println("Line: " + line);
}
} catch (IOException e) {
System.out.println("File not found!");
}
```
### 4. Real-Life Example
**Example 4: The High Score Tracker**
Imagine a game where you save the player's name and score.
```java
String data = "Player1: 5000";
Files.writeString(Path.of("highscore.txt"), data);
```
### 5. Future Hint
**Example 5: Databases (Future Hint)**
For tiny projects, files are great. But if you have millions of users, files become too slow and messy. That's when we use **Databases** (like SQL). Think of a database as a file handling system on steroids!