Java IO

Delete a file or directory in Java

This Java example shows how to delete a file or directory using Java. It also shows how to delete a directory recursively.

How to delete a file in Java?

a) Delete a file using java.io.File class

1) Delete file using delete() method

Use delete() method of File class to delete a file.

This method deletes a file or directory denoted by the path. If the path points to a directory, it must be empty. If the file or directory is deleted, delete() method returns true. If the file or directory cannot be deleted, it returns false.

Please note that delete() method may throw java.lang.SecurityException if delete access is denied.

2) Delete a file when Virtual Machine exits

To delete a file when virtual machine is terminated, use

This method requests the file represented by the path to be deleted when virtual machine is terminated.

b) Delete a file using Apache Commons IO FileUtils

If you are using Apache Commons IO library, use deleteQuietly() method of FileUtils class.

This method deletes the file and returns true if the file is deleted successfully. It never throws any exception. When the file cannot be deleted, it returns false.

Warning: If the file denoted by the path is a directory, deleteQuietly method will delete it recursively.

How to delete a directory in Java?

a) Delete directory using java.io.File class

Use delete() method of java.io.File class to delete a directory.

This method returns true if the directory is deleted, false otherwise.

Note: The directory must be empty before we can delete it. If directory is not empty, delete() method does not delete it and returns false.

How to delete directory recursively?

To delete a directory recursively including all its sub-directories and files, use following code.

b) Delete directory using Apache Commons IO FileUitls class

Use deleteDirectory method of FileUtils class to delete a directory recursively.

Here is the example code to delete a directory recursively.

You can also use deleteQuietly() method to delete a directory recursively.

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: