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.
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.
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.
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.
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);
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.
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