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.walkmethod to walk through all the files of the directory. This method returns a stream withPaths. -
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 directoryFiles.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