Last Updated : 23 Jul, 2025
The class named java.io.File represents a file or directory (path names) in the system. This class provides methods to perform various operations on files/directories.
The delete() method of the File class deletes the files and empty directory represented by the current File object. If a directory is not empty or contain files then that cannot be deleted directly. First, empty the directory, then delete the folder.
Suppose there exists a directory with path C:\\GFG. The following image displays the files and directories present inside GFG folder. The subdirectory Ritik contains a file named Logistics.xlsx and subdirectory Rohan contains a file named Payments.xlsx.
GFG DirectoryThe following java programs illustrate how to delete a directory.
Method 1: using delete() to delete files and empty folders
// Java program to delete a directory
import java.io.File;
class DeleteDirectory {
// function to delete subdirectories and files
public static void deleteDirectory(File file)
{
// store all the paths of files and folders present
// inside directory
for (File subfile : file.listFiles()) {
// if it is a subfolder,e.g Rohan and Ritik,
// recursively call function to empty subfolder
if (subfile.isDirectory()) {
deleteDirectory(subfile);
}
// delete files and empty subfolders
subfile.delete();
}
}
public static void main(String[] args)
{
// store file path
String filepath = "C:\\GFG";
File file = new File(filepath);
// call deleteDirectory function to delete
// subdirectory and files
deleteDirectory(file);
// delete main GFG folder
file.delete();
}
}
Output
Following is the image of C drive where no GFG folder is present.
GFG folder deleted successfullyMethod 2: using deleteDirectory() method from commons-io
To use deleteDirectory() method you need to add a commons-io dependency to maven project.
Java<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
// Java program to delete a directory
import java.io.File;
import org.apache.commons.io.FileUtils;
class DeleteDirectory {
public static void main(String[] args)
{
// store file path
String filepath = "C:\\GFG";
File file = new File(filepath);
// call deleteDirectory method to delete directory
// recursively
FileUtils.deleteDirectory(file);
// delete GFG folder
file.delete();
}
}
Output
Following is the image of C drive where no GFG folder is present.
GFG folder deleted SuccessfullyRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4