Java Delete Files
Learn how to delete files and directories in Java
🗑️ Deleting Files in Java
Java allows you to delete files and directories using the File class delete() method. You can remove single files, empty directories, or entire directory trees with proper safety checks and error handling.
// Delete a file
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File file = new File("unwanted.txt");
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Failed to delete file.");
}
}
}
Output:
File deleted: unwanted.txt
File Deletion Methods
delete()
Delete files and empty directories
file.delete();
exists()
Check if file exists before deleting
file.exists();
isDirectory()
Check if path is a directory
file.isDirectory();
listFiles()
Get files in directory for deletion
file.listFiles();
🔹 Basic File Deletion
Delete a single file with safety checks:
import java.io.File;
public class SafeFileDeletion {
public static void main(String[] args) {
File fileToDelete = new File("temp.txt");
// Check if file exists before attempting deletion
if (fileToDelete.exists()) {
System.out.println("File found: " + fileToDelete.getName());
System.out.println("File size: " + fileToDelete.length() + " bytes");
// Attempt to delete the file
if (fileToDelete.delete()) {
System.out.println("✅ File deleted successfully!");
} else {
System.out.println("❌ Failed to delete the file.");
System.out.println("Check file permissions or if file is in use.");
}
} else {
System.out.println("File does not exist: " + fileToDelete.getName());
}
}
}
Output:
File found: temp.txt
File size: 25 bytes
✅ File deleted successfully!
🔹 Deleting Multiple Files
Delete several files using an array or list:
import java.io.File;
public class MultipleFileDeletion {
public static void main(String[] args) {
String[] filesToDelete = {"file1.txt", "file2.txt", "file3.txt", "old_data.log"};
System.out.println("Deleting multiple files...");
System.out.println("==========================");
int deletedCount = 0;
int notFoundCount = 0;
for (String fileName : filesToDelete) {
File file = new File(fileName);
if (file.exists()) {
if (file.delete()) {
System.out.println("✅ Deleted: " + fileName);
deletedCount++;
} else {
System.out.println("❌ Failed to delete: " + fileName);
}
} else {
System.out.println("⚠️ Not found: " + fileName);
notFoundCount++;
}
}
System.out.println("==========================");
System.out.println("Summary: " + deletedCount + " deleted, " + notFoundCount + " not found");
}
}
Output:
Deleting multiple files...
==========================
✅ Deleted: file1.txt
✅ Deleted: file2.txt
⚠️ Not found: file3.txt
✅ Deleted: old_data.log
==========================
Summary: 3 deleted, 1 not found
🔹 Deleting Empty Directories
Remove empty directories using the same delete() method:
import java.io.File;
public class DirectoryDeletion {
public static void main(String[] args) {
File directory = new File("EmptyFolder");
if (directory.exists()) {
if (directory.isDirectory()) {
System.out.println("Found directory: " + directory.getName());
// Check if directory is empty
File[] files = directory.listFiles();
if (files != null && files.length == 0) {
if (directory.delete()) {
System.out.println("✅ Empty directory deleted successfully!");
} else {
System.out.println("❌ Failed to delete directory.");
}
} else {
System.out.println("⚠️ Directory is not empty. Cannot delete.");
System.out.println("Contains " + (files != null ? files.length : 0) + " items.");
}
} else {
System.out.println("Path is not a directory: " + directory.getName());
}
} else {
System.out.println("Directory does not exist: " + directory.getName());
}
}
}
Output:
Found directory: EmptyFolder
✅ Empty directory deleted successfully!
🔹 Deleting Directory with Contents
Recursively delete directories and all their contents:
import java.io.File;
public class RecursiveDeletion {
public static void main(String[] args) {
File directory = new File("FolderToDelete");
if (directory.exists()) {
System.out.println("Deleting directory: " + directory.getName());
if (deleteDirectory(directory)) {
System.out.println("✅ Directory and all contents deleted!");
} else {
System.out.println("❌ Failed to delete directory completely.");
}
} else {
System.out.println("Directory does not exist: " + directory.getName());
}
}
// Recursive method to delete directory and all contents
public static boolean deleteDirectory(File dir) {
if (dir.isDirectory()) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
// Recursively delete subdirectory
deleteDirectory(file);
} else {
// Delete file
if (file.delete()) {
System.out.println("Deleted file: " + file.getName());
}
}
}
}
}
// Delete the directory itself
return dir.delete();
}
}
Output:
Deleting directory: FolderToDelete
Deleted file: document.txt
Deleted file: image.jpg
✅ Directory and all contents deleted!
🔹 Safe Deletion with User Confirmation
Add user confirmation for important file deletions:
import java.io.File;
import java.util.Scanner;
public class ConfirmDeletion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
File file = new File("important.txt");
if (file.exists()) {
System.out.println("File to delete: " + file.getName());
System.out.println("File size: " + file.length() + " bytes");
System.out.println("Last modified: " + new java.util.Date(file.lastModified()));
System.out.print("Are you sure you want to delete this file? (yes/no): ");
String response = scanner.nextLine().toLowerCase();
if (response.equals("yes") || response.equals("y")) {
if (file.delete()) {
System.out.println("✅ File deleted successfully!");
} else {
System.out.println("❌ Failed to delete file.");
}
} else {
System.out.println("File deletion cancelled.");
}
} else {
System.out.println("File not found: " + file.getName());
}
scanner.close();
}
}
Output:
File to delete: important.txt
File size: 1024 bytes
Last modified: Thu Jan 15 10:30:45 EST 2024
Are you sure you want to delete this file? (yes/no): yes
✅ File deleted successfully!
🔹 Important Safety Tips
⚠️ File Deletion Best Practices:
- Always check if file exists: Use exists() before delete()
- Handle return values: delete() returns true/false for success
- Be careful with directories: Only empty directories can be deleted directly
- No undo operation: Deleted files cannot be recovered easily
- Check permissions: Ensure your program has delete permissions
- Close file streams: Files in use cannot be deleted