This post will discuss how to delete all files in a directory in Java.

1. Using FileUtils class

The FileUtils class from Apache Commons IO offers several handy file manipulation utilities. You can use the FileUtils.cleanDirectory() method to recursively delete all files and subdirectories within a directory, without deleting the directory itself.

Download Code

 
To delete a directory recursively and everything in it, you can use the FileUtils.deleteDirectory() method.

Download Code

 
Alternatively, you can use the FileUtils.forceDelete() method to delete a directory and all subdirectories.

Download Code

2. Using File.delete() method

The File.delete() method deletes the file or directory denoted by the specified pathname. There are numerous ways to conditionally delete files and subdirectories in a directory using it.

For instance, the following solution only deletes files within the main directory, and all subdirectories remain untouched.

Download Code

 
If you use Java 8 or above, you can use:

Download Code

 
You can easily extend the solution to recursively delete all files and subdirectories within a directory. Note that you can delete a directory using the File.delete() method if and only if the directory is empty.

Download Code

 
Here’s a version using the Stream API. It takes advantage of the Files.walk() method and deletes all files and subdirectories within a directory, along with the directory itself.

Download Code

 
If you need to delete “only files” from the directory and all its subdirectories, you can do as follows:

Download Code

That’s all about deleting all files in a directory in Java.