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
import java.io.File;
public class FileCreation {
public static void main(String[] args) {
// Method 1: Absolute path
File file1 = new File("C:\\Users\\data\\report.txt"); // Windows
File file1Unix = new File("/home/user/data/report.txt"); // Linux/Mac
// Method 2: Relative path (relative to project directory)
File file2 = new File("data.txt");
// Method 3: Parent directory + filename
File file3 = new File("C:\\Users\\data", "report.txt");
// Method 4: Parent File + child name
File parentDir = new File("C:\\Users\\data");
File file4 = new File(parentDir, "report.txt");
// Important: Creating a File object does NOT create the file on disk!
File ghost = new File("nonexistent.txt");
System.out.println("File object created: " + ghost.getName());
System.out.println("Actually exists on disk? " + ghost.exists());
}
}Output:
Checking File Properties
import java.io.File;
import java.util.Date;
public class FileProperties {
public static void main(String[] args) {
File file = new File("src/Main.java"); // Adjust path to an existing file
System.out.println("=== File Properties ===\n");
// Basic info
System.out.println("Name: " + file.getName());
System.out.println("Path: " + file.getPath());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("Parent: " + file.getParent());
// Existence checks
System.out.println("\n--- Existence ---");
System.out.println("Exists? " + file.exists());
System.out.println("Is File? " + file.isFile());
System.out.println("Is Directory? " + file.isDirectory());
System.out.println("Is Hidden? " + file.isHidden());
// Size and time
System.out.println("\n--- Size & Time ---");
System.out.println("Size (bytes): " + file.length());
System.out.println("Last Modified: " + new Date(file.lastModified()));
// Permissions
System.out.println("\n--- Permissions ---");
System.out.println("Can Read? " + file.canRead());
System.out.println("Can Write? " + file.canWrite());
System.out.println("Can Execute? " + file.canExecute());
// Disk space (of the partition)
System.out.println("\n--- Disk Space ---");
System.out.printf("Total Space: %.2f GB%n", file.getTotalSpace() / 1e9);
System.out.printf("Free Space: %.2f GB%n", file.getFreeSpace() / 1e9);
System.out.printf("Usable Space: %.2f GB%n", file.getUsableSpace() / 1e9);
}
}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
import java.io.File;
import java.io.IOException;
public class CreateFilesAndDirs {
public static void main(String[] args) {
System.out.println("=== Creating Files and Directories ===\n");
// 1. Create a new file
File newFile = new File("test_output.txt");
try {
if (newFile.createNewFile()) {
System.out.println("✓ File created: " + newFile.getName());
} else {
System.out.println("✗ File already exists: " + newFile.getName());
}
} catch (IOException e) {
System.out.println("Error creating file: " + e.getMessage());
}
// 2. Create a single directory
File dir = new File("output");
if (dir.mkdir()) {
System.out.println("✓ Directory created: " + dir.getName());
} else {
System.out.println("✗ Directory exists or parent missing: " + dir.getName());
}
// 3. Create nested directories (parent + child)
File nestedDirs = new File("output/reports/2024/january");
if (nestedDirs.mkdirs()) { // Note: mkdirS (plural)
System.out.println("✓ Nested directories created: " + nestedDirs.getPath());
} else {
System.out.println("✗ Directories already exist: " + nestedDirs.getPath());
}
// 4. Create a temporary file
try {
File tempFile = File.createTempFile("myapp_", ".tmp");
System.out.println("✓ Temp file: " + tempFile.getAbsolutePath());
tempFile.deleteOnExit(); // Auto-delete when JVM exits
} catch (IOException e) {
System.out.println("Error creating temp file: " + e.getMessage());
}
// Cleanup
newFile.delete();
}
}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
Recursive Directory Traversal
Renaming and Moving Files
import java.io.File;
import java.io.IOException;
public class RenameMove {
public static void main(String[] args) throws IOException {
// Setup: create test files
File original = new File("original.txt");
original.createNewFile();
File dir = new File("backup");
dir.mkdir();
System.out.println("=== Rename and Move Operations ===\n");
// Rename (same directory)
File renamed = new File("renamed.txt");
if (original.renameTo(renamed)) {
System.out.println("✓ Renamed: original.txt → renamed.txt");
}
// Move (different directory) — renameTo can also move
File moved = new File("backup/renamed.txt");
if (renamed.renameTo(moved)) {
System.out.println("✓ Moved: renamed.txt → backup/renamed.txt");
}
// Cleanup
moved.delete();
dir.delete();
System.out.println("\n✓ Cleanup complete");
}
}Deleting Files and Directories
import java.io.File;
import java.io.IOException;
public class DeleteOperations {
// Recursively delete a directory and all contents
static boolean deleteRecursive(File file) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
deleteRecursive(child);
}
}
}
boolean deleted = file.delete();
System.out.println((deleted ? " ✓ Deleted: " : " ✗ Failed: ") + file.getPath());
return deleted;
}
public static void main(String[] args) throws IOException {
// Create test structure
new File("testdir/sub1/deep").mkdirs();
new File("testdir/sub2").mkdirs();
new File("testdir/file1.txt").createNewFile();
new File("testdir/sub1/file2.txt").createNewFile();
new File("testdir/sub1/deep/file3.txt").createNewFile();
System.out.println("Created test directory structure.");
System.out.println("\n=== Deleting recursively ===");
// Note: file.delete() only works on EMPTY directories!
File testDir = new File("testdir");
System.out.println("Can delete non-empty dir directly? " + testDir.delete());
System.out.println("\nRecursive delete:");
deleteRecursive(testDir);
}
}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
import java.io.File;
import java.io.IOException;
public class PathOperations {
public static void main(String[] args) throws IOException {
File file = new File("./src/../data/./report.txt");
System.out.println("=== Path Operations ===\n");
System.out.println("Original path: " + file.getPath());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Canonical path: " + file.getCanonicalPath());
// Canonical path resolves . and .. to give the true path
System.out.println("\n--- Path Components ---");
System.out.println("getName(): " + file.getName());
System.out.println("getParent(): " + file.getParent());
System.out.println("\n--- Separators ---");
System.out.println("File.separator: '" + File.separator + "'");
System.out.println("File.pathSeparator: '" + File.pathSeparator + "'");
// separator: / (Unix) or \ (Windows) — for file paths
// pathSeparator: : (Unix) or ; (Windows) — for PATH variable
System.out.println("\n--- System Roots ---");
File[] roots = File.listRoots();
for (File root : roots) {
System.out.printf("Root: %s | Total: %.1f GB | Free: %.1f GB%n",
root.getPath(),
root.getTotalSpace() / 1e9,
root.getFreeSpace() / 1e9);
}
}
}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
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.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for File Class in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, file, handling, class
Related Java Master Course Topics