Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete directories recursively in Java

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?

like image 769
paweloque Avatar asked Apr 22 '09 22:04

paweloque


People also ask

How do I delete a directory recursively?

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.

How do I delete multiple folders 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 empty a directory in Java?

You can directly use: FileUtils. deleteDirectory(<File object of directory>); This function will directory delete the folder and all files in it.


2 Answers

You should check out Apache's commons-io. It has a FileUtils class that will do what you want.

FileUtils.deleteDirectory(new File("directory")); 
like image 150
Steve K Avatar answered Sep 22 '22 04:09

Steve K


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); } 
like image 31
erickson Avatar answered Sep 21 '22 04:09

erickson