How to delete a directory and its contents in Java

In Java, we can loop through all the files and folders inside a directory and delete it. To delete a directory:

  • Use the Files.walk method to walk through all the files of the directory. This method returns a stream with Paths.

  • All the files are traversed in depth-first order. Reverse the stream and delete it from inner files.

  • Call Files.delete(path) to delete the file or directory.

Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
public class Main {
public static void main(String[] args) throws IOException {
Path dir = Paths.get("path"); //path to the directory
Files
.walk(dir) // Traverse the file tree in depth-first order
.sorted(Comparator.reverseOrder())
.forEach(path -> {
try {
System.out.println("Deleting: " + path);
Files.delete(path); //delete each file or directory
} catch (IOException e) {
e.printStackTrace();
}
});
}
}

In the above code, we looped through all the filesnormal files and directory of the directory and deleted them. This also deletes the current directory.