Supposing I have a File f
that represents a directory, then f.delete()
will only delete the directory if it is empty. I've found a couple of examples online that use File.listFiles()
or File.list()
to get all the files in the directory and then recursively traverses the directory structure and delete all the files. However, since it's possible to create infinitely recursive directory structures (in both Windows and Linux (with symbolic links)) presumably it's possible that programs written in this style might never terminate.
So, is there a better way to write such a program so that it doesn't fall into these pitfalls? Do I need to keep track of everywhere I've traversed and make sure I don't go around in circles or is there a nicer way?
Update: In response to some of the answers (thanks guys!) - I'd rather the code didn't follow symbolic links and stayed within the directory it was supposed to delete. Can I rely on the Commons-IO implementation to do that, even in the Windows case?
The non-empty directory means the directory with files or subdirectories. We can delete the directory by using the Delete() method of the Directory class.
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.
Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder. Then you should be able to delete the folder by using index.
rmdir is a command-line utility for deleting empty directories, while with rm you can remove directories and their contents recursively. If a directory or a file within the directory is write-protected, you will be prompted to confirm the deletion.
If you really want your recursive directory deletion to follow through symbolic links, then I don't think there is any platform independent way of doing so without keeping track of all the directories you have traversed.
However, in pretty much every case I can think of you would just want to delete the actual symbolic link pointing to the directory rather than recursively following through the symbolic link.
If this is the behaviour you want then you can use the FileUtils.deleteDirectory method in Apache Commons IO.
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