Java Notes
Complete guide to the java.io.File class — creating File objects, checking file properties, creating/deleting files and directories, listing contents, and file path operations.
What is the File Class?
The java.io.File class represents a file or directory path in the file system. It does NOT represent the file's content — it represents the abstract pathname (name and location) of a file or directory.
Important: The File class doesn't actually read or write file content. It handles file metadata operations:
- Check if a file exists
- Create/delete files and directories
- Get file size, permissions, modification time
- List directory contents
- Rename and move files
Creating File Objects
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
Checking File Properties
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output (example):
| Name | Main.java |
| Path | src\Main.java |
| Absolute Path | C:\Projects\MyApp\src\Main.java |
| Parent | src |
| Size (bytes) | 2456 |
| Last Modified | Mon Jan 15 10:30:45 IST 2024 |
| Total Space | 476.94 GB |
| Free Space | 234.12 GB |
| Usable Space | 234.12 GB |
Creating Files and Directories
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| ✓ File created | test_output.txt |
| ✓ Directory created | output |
| ✓ Nested directories created | output\reports\2024\january |
| ✓ Temp file | C:\Users\user\AppData\Local\Temp\myapp_1234567890.tmp |
Listing Directory Contents
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Recursive Directory Traversal
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Renaming and Moving Files
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Deleting Files and Directories
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| ✓ Deleted | testdir\sub1\deep\file3.txt |
| ✓ Deleted | testdir\sub1\deep |
| ✓ Deleted | testdir\sub1\file2.txt |
| ✓ Deleted | testdir\sub1 |
| ✓ Deleted | testdir\sub2 |
| ✓ Deleted | testdir\file1.txt |
| ✓ Deleted | testdir |
File Path Operations
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output (Windows):
| Original path | .\src\..\data\.\report.txt |
| Absolute path | C:\Projects\MyApp\.\src\..\data\.\report.txt |
| Canonical path | C:\Projects\MyApp\data\report.txt |
| getName() | report.txt |
| getParent() | .\src\..\data\. |
| File.separator | '\' |
| File.pathSeparator | ';' |
| Root | C:\ | Total: 476.9 GB | Free: 234.1 GB |
| Root | D:\ | Total: 931.5 GB | Free: 567.2 GB |
Real-World Example: File Organizer
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Common Mistakes
1. Assuming File object creation creates the file
// ❌ WRONG assumption
File file = new File("data.txt");
// File does NOT exist on disk yet!
// You must call createNewFile() or write to it
// ✅ CORRECT
File file = new File("data.txt");
file.createNewFile(); // Now it exists2. Not checking if operations succeeded
// ❌ BAD: Ignoring return value
file.delete(); // Did it actually delete? We don't know!
// ✅ GOOD: Check the result
if (!file.delete()) {
System.err.println("Failed to delete: " + file.getPath());
}3. Using hardcoded path separators
// ❌ BAD: Won't work on Linux/Mac
File file = new File("C:\\Users\\data\\file.txt");
// ✅ GOOD: Use File.separator or forward slashes
File file = new File("data" + File.separator + "file.txt");
// OR: Java accepts forward slashes on all platforms
File file = new File("data/file.txt");File Class vs NIO (java.nio.file.Path)
| Feature | File (java.io) | Path (java.nio) |
|---|---|---|
| Introduced | Java 1.0 | Java 7 |
| Symbolic links | No support | Full support |
| File attributes | Limited | Comprehensive |
| Error handling | Returns boolean | Throws descriptive exceptions |
| Watch service | Not available | Available |
| Performance | Good | Better for large operations |
| Recommendation | Legacy code | New code should use this |
Interview Questions
Q1: Does creating a File object create the file on disk?
Answer: No. new File("test.txt") only creates an in-memory object representing the path. To actually create the file, call file.createNewFile() or write to it using a stream.
Q2: What is the difference between mkdir() and mkdirs()?
Answer: mkdir() creates only the specified directory and fails if parent directories don't exist. mkdirs() creates all necessary parent directories along with the target directory (like mkdir -p in Linux).
Q3: What is the difference between getPath(), getAbsolutePath(), and getCanonicalPath()?
Answer: getPath() returns the path as specified in the constructor. getAbsolutePath() resolves relative paths against the current directory but keeps . and ... getCanonicalPath() resolves ., .., symbolic links and returns the unique, normalized path.
Q4: Why does File.delete() return a boolean instead of throwing an exception?
Answer: It's a design choice from Java 1.0. The boolean return makes it easy to ignore failures (which is actually bad practice). The newer Files.delete() in NIO throws an IOException with details about why deletion failed, which is the preferred approach in modern Java.
Q5: How do you delete a non-empty directory?
Answer: You must first recursively delete all files and subdirectories inside it, then delete the directory itself. File.delete() only works on empty directories. Alternatively, use Files.walk() from NIO for a cleaner approach.
Continue the lesson path