Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete directory content in Java? [duplicate]

After enumerating a directory, I now need to delete all the files.

I used:

final File[] files = outputFolder.listFiles(); files.delete(); 

But this hasn't deleted the directory.

like image 381
lola Avatar asked Oct 14 '11 13:10

lola


People also ask

How can we delete all files in a directory in Java?

You can use the FileUtils. cleanDirectory() method to recursively delete all files and subdirectories within a directory, without deleting the directory itself. To delete a directory recursively and everything in it, you can use the FileUtils. deleteDirectory() method.

How do I delete a non-empty directory in Java?

In Java, to delete a non-empty directory, we must first delete all the files present in the directory. Then, we can delete the directory. In the above example, we have used the for-each loop to delete all the files present in the directory.

How do you delete a file if already exists in Java?

files. deleteifexists(Path p) method defined in Files package: This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is not empty. Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist.


2 Answers

You have to do this for each File:

public static void deleteFolder(File folder) {     File[] files = folder.listFiles();     if(files!=null) { //some JVMs return null for empty dirs         for(File f: files) {             if(f.isDirectory()) {                 deleteFolder(f);             } else {                 f.delete();             }         }     }     folder.delete(); } 

Then call

deleteFolder(outputFolder); 
like image 111
NCode Avatar answered Oct 29 '22 18:10

NCode


To delete folder having files, no need of loops or recursive search. You can directly use:

FileUtils.deleteDirectory(<File object of directory>); 

This function will directory delete the folder and all files in it.

like image 44
Dhruv Bansal Avatar answered Oct 29 '22 17:10

Dhruv Bansal