Is there a way to delete entire directories recursively in Java?
In the normal case it is possible to delete an empty directory. However when it comes to deleting entire directories with contents, it is not that simple anymore.
How do you delete entire directories with contents in Java?
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
The delete() method of the File class deletes the file/directory represented by the current File object. This ListFiles() method of the File class returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.
You can directly use: FileUtils. deleteDirectory(<File object of directory>); This function will directory delete the folder and all files in it.
You should check out Apache's commons-io. It has a FileUtils class that will do what you want.
FileUtils.deleteDirectory(new File("directory"));
With Java 7, we can finally do this with reliable symlink detection. (I don't consider Apache's commons-io to have reliable symlink detection at this time, as it doesn't handle links on Windows created with mklink
.)
For the sake of history, here's a pre-Java 7 answer, which follows symlinks.
void delete(File f) throws IOException { if (f.isDirectory()) { for (File c : f.listFiles()) delete(c); } if (!f.delete()) throw new FileNotFoundException("Failed to delete file: " + f); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With