File I/O: Reading and Writing Data
Up until now, all the data your programs processed disappeared as soon as the program stopped. File I/O (Input/Output) allows you to save data to a .txt or .log file and read it back later. This is how you create persistent settings, logs, or databases.
1. The Core Classes
Java provides several ways to handle files, but the most common modern approach uses these three:
File: Used to check if a file exists, get its path, or delete it.FileWriter/BufferedWriter: Used to write text into a file.Scanner/BufferedReader: Used to read text from a file.
2. Writing to a File
When writing, you should wrap your code in a try-with-resources block. This ensures the file is closed automatically, preventing memory leaks or file corruption.
import java.io.FileWriter;
import java.io.IOException;
try (FileWriter writer = new FileWriter("config.txt")) {
writer.write("theme=dark\n");
writer.write("font=JetBrains Mono\n");
System.out.println("Settings saved successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing.");
}
Tip: Use
new FileWriter("file.txt", true)to append to a file instead of overwriting it!
3. Reading from a File
Reading is often done using the Scanner class because it makes it easy to read line-by-line.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
try {
File myFile = new File("config.txt");
Scanner reader = new Scanner(myFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
💻 Full Practical Example: The Simple Logger
Copy this code to create a basic system that logs timestamps to a file:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
public class Logger {
public static void main(String[] args) {
logEvent("Application started");
logEvent("User 'c0der' logged in");
}
public static void logEvent(String event) {
// 'true' means append to the file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("log.txt", true))) {
String timestamp = LocalDateTime.now().toString();
writer.write("[" + timestamp + "] " + event);
writer.newLine();
} catch (IOException e) {
System.err.println("Could not write to log: " + e.getMessage());
}
}
}
4. Useful File Methods
file.exists(): Returnstrueif the file is there.file.delete(): Deletes the file.file.getName(): Returns the filename.file.getAbsolutePath(): Returns the full system path (e.g.,/home/ahmed/log.txt).
💡 Challenge: The Note Taker
Write a program that:
- Asks the user for a string of text.
- Saves that text into a file named
notes.txt. - Immediately reads the file back and prints: "Your saved note: [Content]".
- Bonus: Use a loop to let the user enter multiple notes until they type "exit".