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 Directory
The following java programs illustrate how to delete a directory.
Method 1: using delete() to delete files and empty folders
- Provide the path of a directory.
- Call user-defined method deleteDirectory() to delete all the files and subfolders.
Java
import java.io.File;
class DeleteDirectory {
public static void deleteDirectory(File file)
{
for (File subfile : file.listFiles()) {
if (subfile.isDirectory()) {
deleteDirectory(subfile);
}
subfile.delete();
}
}
public static void main(String[] args)
{
String filepath = "C:\\GFG" ;
File file = new File(filepath);
deleteDirectory(file);
file.delete();
}
}
|
Output
Following is the image of C drive where no GFG folder is present.

GFG folder deleted successfully
Method 2: using deleteDirectory() method from commons-io
To use deleteDirectory() method you need to add a commons-io dependency to maven project.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
Java
import java.io.File;
import org.apache.commons.io.FileUtils;
class DeleteDirectory {
public static void main(String[] args)
{
String filepath = "C:\\GFG" ;
File file = new File(filepath);
FileUtils.deleteDirectory(file);
file.delete();
}
}
|
Output
Following is the image of C drive where no GFG folder is present.

GFG folder deleted Successfully
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
05 Jan, 2023
Like Article
Save Article