Skip to content

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?

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

We can use the delete method of the 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, the delete method returns true. If the file or directory could not be deleted, it returns false.

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

How to delete a file when the Virtual Machine exits?

To delete a file when the virtual machine is terminated, use the deleteOnExit method.

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

2) Delete a file using the Apache Commons IO FileUtils

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

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

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

How to delete a directory in Java?

1) Delete directory using java.io.File class

Use the delete method of the 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 the directory is not empty, the delete method does not delete it and returns false.

How to delete a directory recursively?

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

2) Delete directory using the Apache Commons IO FileUitls class

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

Here is the example code to delete a directory recursively.

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

This example is a part of the Java File class tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.