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?
i coded this routine that has 3 safety criteria for safer use.
You could use:
org.apache.commons.io.FileUtils.deleteQuietly(destFile);
Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. The difference between File.delete() and this method are: A directory to be deleted does not have to be empty. No exceptions are thrown when a file or directory cannot be deleted.
You should check out Apache's commons-io. It has a FileUtils class that will do what you want.
While files can easily be deleted using file.delete(), directories are required to be empty to be deleted. Use recursion to do this easily. For example:
Guava had
Files.deleteRecursively(File)
supported until Guava 9.From Guava 10:
Therefore, there is no such method in Guava 11.
Or if you want to handle the
IOException
: