Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting non-empty directories in Java

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?

like image 859
Martin McNulty Avatar asked Feb 18 '09 11:02

Martin McNulty


People also ask

How do I delete a non empty directory?

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.

How do you delete a directory in Java?

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.

How do I delete multiple folders in Java?

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.

Does rmdir delete non empty directory?

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.


1 Answers

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.

like image 189
Il-Bhima Avatar answered Oct 06 '22 23:10

Il-Bhima