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?
Two ways to fail with symlinks and the above code... and don't know the solution.
Way #1
Run this to create a test:
Here you see your test file and test directory:
Then run your commons-io deleteDirectory(). It crashes saying the file is not found. Not sure what the other examples do here. The Linux rm command would simply delete the link, and rm -r on the directory would also.
Way #2
Run this to create a test:
Here you see your test file and test directory:
Then run your commons-io deleteDirectory() or the example code people posted. It deletes not only the directory, but your testfile which is outside the directory being deleted. (It dereferences the directory implicitly, and deletes the contents). rm -r would delete the link only. You need to use something like this delete the dereferenced files: "find -L dirtodelete -type f -exec rm {} \;".
Without Commons IO and < Java SE 7
In Java 7+ you can use
Files
class. Code is very simple:Java 7 added support for walking directories with symlink handling:
I use this as a fallback from platform-specific methods (in this untested code):
(SystemUtils is from Apache Commons Lang. Processes is private but its behavior should be obvious.)
Maybe a solution for this problem might be to reimplement the delete method of the File class using the code from erickson's answer: