Java Program to Delete a DirectoryJava 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() MethodThe 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. DeleteDirectoryExample1.java Output: By Using the File.deleteDirectory() MethodThere 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. DeleteDirectoryExample2.java Output: |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India