Files.delete: Deleting Files and Directories
You'll learn how to permanently remove files and empty directories from the filesystem using Files.delete.
The Core Idea
The Files.delete method provides a straightforward way to remove files or empty directories from disk. Unlike older File.delete() approaches, it throws specific exceptions when something goes wrong, making error handling more precise and debuggable.
Think of it like a strict librarian removing a book from the catalog—if the book doesn't exist, you get a clear complaint rather than silence.
Basic Usage
import java.nio.file.*;
import java.io.IOException;
Path filePath = Paths.get("temp.txt");
try {
Files.delete(filePath);
System.out.println("File deleted successfully");
} catch (NoSuchFileException e) {
System.out.println("File doesn't exist: " + e.getMessage());
} catch (IOException e) {
System.out.println("Delete failed: " + e.getMessage());
}
Handling NoSuchFileException
The most common exception you'll encounter is NoSuchFileException, thrown when you attempt to delete a file or directory that doesn't exist:
Path missing = Paths.get("nonexistent.txt");
try {
Files.delete(missing);
} catch (NoSuchFileException e) {
// Handle missing file scenario
System.out.println("Cannot delete - file not found");
}
Important Constraints
- Directories must be empty: You cannot delete a directory containing files or subdirectories
- Immediate effect: The deletion happens synchronously—when the method returns, the file is gone
- No recovery: Unlike some systems with "recycle bins," this is permanent deletion
Key Takeaway: Files.delete removes files and empty directories, throwing NoSuchFileException if the target doesn't exist, enabling precise error handling for filesystem operations.