Java Program to Delete a Directory
Java provides the File class for representing a file or directory in the system. The File class is available in java.io package. In order to perform operations on files or directories, the File class provide several useful methods.
The delete() method of the File class is one of the most important methods which is used to delete the files and empty directories represented by the current File object.
Note: When a directory contains some files, it cannot be deleted directly by using the delete() method. For deleting it, we first empty the directory and then delete the folder.
However, we have two ways to delete the files or directories in the system, i.e., using the delete() method of File and using the deleteDirectory() method from commons-io.
Let's understand both the ways to understand how we can delete a directory in the system:
By using the File.delete() Method
The delete() method of the File class is used for deleting a directory. Before using the delete() method, we first call a user-defined method, i.e., deleteDirectory(), that will delete the subfile or subdirectory.
Let's take an example to understand how we can delete a directory by using the delete() method.
By Using the File.deleteDirectory() Method
There is another way of deleting a directory in Java. We can use the deleteDirectory() method from the commons-io. In order to use the deleteDirectory() method, we need to add the following dependency to maven project:
Let's take an example to understand how we can use commons-io for deleting a directory.