- Understand file paths and the File class
- Learn how to read from text files using various methods
- Learn how to write to text files
- Master basic file operations (create, delete, check existence)
- Handle common file I/O exceptions properly
File I/O Basics
Programs need to read and write files—configuration files, user data, logs, reports. Let's see how Java handles file input and output.
Understanding File Paths
Before working with files, you need to know how to locate them.
The File Class
The File class represents a file or directory path:
import java.io.File;
// Creating File objects
File file1 = new File("data.txt"); // Relative path
File file2 = new File("/home/user/documents/data.txt"); // Absolute path
File file3 = new File("folder", "data.txt"); // Parent and child
Checking File Properties
File file = new File("data.txt");
// Does it exist?
if (file.exists()) {
System.out.println("File exists!");
// Is it a file or directory?
System.out.println("Is file: " + file.isFile());
System.out.println("Is directory: " + file.isDirectory());
// File properties
System.out.println("Size: " + file.length() + " bytes");
System.out.println("Can read: " + file.canRead());
System.out.println("Can write: " + file.canWrite());
System.out.println("Absolute path: " + file.getAbsolutePath());
}
Reading Text Files
Method 1: Using Scanner
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public void readWithScanner(String filename) {
try {
File file = new File(filename);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
System.out.println("File read successfully!");
} catch (FileNotFoundException e) {
System.out.println("Error: File '" + filename + "' not found");
}
}
Method 2: Using BufferedReader (Recommended)
import java.io.*;
public void readWithBufferedReader(String filename) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + filename);
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
Writing Text Files
Method 1: Using PrintWriter
import java.io.*;
public void writeWithPrintWriter(String filename) {
try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
writer.println("First line");
writer.println("Second line");
writer.printf("Number: %d%n", 42);
System.out.println("File written successfully!");
} catch (IOException e) {
System.out.println("Error writing file: " + e.getMessage());
}
}
Method 2: Using BufferedWriter
import java.io.*;
public void writeWithBufferedWriter(String filename) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write("First line");
writer.newLine();
writer.write("Second line");
writer.newLine();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
Appending to Files
// Append mode: pass true as second parameter
try (FileWriter writer = new FileWriter("log.txt", true)) {
writer.write("New log entry\n");
} catch (IOException e) {
e.printStackTrace();
}
File Operations
Creating Files and Directories
File file = new File("newfile.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists");
}
// Create directory
File dir = new File("newfolder");
if (dir.mkdir()) {
System.out.println("Directory created");
}
Deleting Files
File file = new File("oldfile.txt");
if (file.delete()) {
System.out.println("File deleted successfully");
} else {
System.out.println("Failed to delete file");
}
Real-World Example: Contact Manager
import java.io.*;
import java.util.*;
public class ContactManager {
private static final String FILENAME = "contacts.txt";
public void saveContact(String name, String phone) {
try (PrintWriter writer = new PrintWriter(
new FileWriter(FILENAME, true))) {
writer.println(name + "," + phone);
System.out.println("Contact saved!");
} catch (IOException e) {
System.out.println("Error saving contact: " + e.getMessage());
}
}
public void listContacts() {
try (BufferedReader reader = new BufferedReader(
new FileReader(FILENAME))) {
String line;
System.out.println("=== Contacts ===");
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
System.out.println("Name: " + parts[0] + ", Phone: " + parts[1]);
}
} catch (FileNotFoundException e) {
System.out.println("No contacts found");
} catch (IOException e) {
System.out.println("Error reading contacts: " + e.getMessage());
}
}
}
Best Practices
- Always use try-with-resources for automatic resource management
- Check file existence before reading
- Handle exceptions properly with meaningful messages
- Close resources explicitly if not using try-with-resources
- Use BufferedReader/Writer for better performance
- Validate file paths to avoid security issues
Key Takeaways
- File class represents file/directory paths
- Scanner and BufferedReader read text files
- PrintWriter and BufferedWriter write text files
- Always handle IOException when working with files
- Try-with-resources ensures proper resource cleanup
- Check file existence with exists() before operations
What's Next?
In the next lesson, you'll learn about streams, binary file operations, and Java NIO for more advanced file handling!
