[!NOTE] Until now, all of our application data existed exclusively in RAM. If we restarted the program, all variables vanished. To permanently persist data (without diving into complex SQL databases), we write it to hard disk files.
The java.io.File class allows us to create and read files from the host Operating System.
Creating and Writing to a File
When writing a file, we utilize the FileWriter class. Remember our lesson on the try-catch block? File operations touch external hardware, meaning they are highly prone to crashing (e.g., hard drive is full, lacking admin permission). Therefore, Java enforces a try-catch block for all I/O operations via Checked Exceptions.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteExample {
public static void main(String[] args) {
// Explicitly required try/catch!
try {
// 1. Target the file (it will create it if it doesn't exist!)
FileWriter myWriter = new FileWriter("filename.txt");
// 2. Write the string payload
myWriter.write("Java File I/O is easier than you think. Logging data to disk...");
// 3. MANDATORY: Close the stream! If you forget this, the data may never actually flush to the disk!
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred. Check permission restrictions.");
e.printStackTrace();
}
}
}
Reading from a File
To read from a file, we can hook our good friend the Scanner up to a File Object, rather than hooking it up to System.in (the keyboard).
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadExample {
public static void main(String[] args) {
// Required to catch specific non-existent files
try {
// 1. Establish the target
File myObj = new File("filename.txt");
// 2. Inform the Scanner to read the File, not the Keyboard!
Scanner myReader = new Scanner(myObj);
// 3. Loop through every line until the end of the file is reached
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
// 4. Free up memory!
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("The requested file was completely missing!");
}
}
}
[!TIP] Getting File Meta Info: Before reading, you can execute
myObj.exists()to check if it's there safely. You can also runmyObj.length()to get the exact file size in bytes to prevent attempting to load a 100GB text file into a 2GB RAM container!
Prefer try-with-resources for File Work
Files, streams, readers, and writers must be closed. Modern Java gives you try-with-resources, which closes resources automatically even when an exception happens.
Writing Safely
Path path = Path.of("notes.txt");
try {
Files.writeString(path, "Learning Java File I/O");
} catch (IOException e) {
System.out.println("Could not write file: " + e.getMessage());
}
Reading Safely
Path path = Path.of("notes.txt");
try {
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
System.out.println("Could not read file: " + e.getMessage());
}
The java.nio.file.Files API is often more convenient for common file tasks than older low-level classes.
Before Reading Large Files
Path path = Path.of("large-log.txt");
long size = Files.size(path);
if (size < 5_000_000) {
String content = Files.readString(path);
}
Common Mistakes
- Forgetting to close readers or writers.
- Reading huge files fully into memory without checking size.
- Hardcoding file paths that only work on one machine.
- Ignoring character encoding when handling user-visible text.
Mini Practice
Write three lines to a text file, read them back, and print only lines that contain the word Java. Then try reading a missing file and handle the error cleanly.
Practice Lab: Write and Read Study Notes
Persist simple text to disk, then read it back safely.
- Create a file path named
study-notes.txt. - Write three lines about what you learned in Java.
- Read the file back line by line.
- Print only lines containing the word
Java. - Try reading a missing file and handle the error cleanly.
Goal: Practice basic persistence, checked exceptions, and safe file reading.
Revision Checkpoint
- File I/O: Moves data between program memory and disk.
- Checked exceptions: File operations often require handling
IOException. - Close resources: Use try-with-resources where possible.
FilesAPI: Convenient for common read/write tasks.- Large files: Avoid reading huge files fully into memory without checking size.
Before the quiz: Explain why closing or flushing a writer matters.