In my application I have written the code to delete the directory from drive but when I inspect the delete function of File it doesn't delete the file. I have written some thing like this
//Code to delete the directory if it exists
File directory = new File("c:\\Report\\");
if(directory.exists())
directory.delete();
the directoryis not in used still it is not able to delete the directory
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.
If the directory is not empty or you do not have permission to delete it, you will see an error message. To remove a directory that is not empty, use the rm command with the -r option for recursive deletion.
Press Shift + Delete to force delete a file or folder If the problem is due to the Recycle Bin, you can select the target file for folder, and press Shift + Delete keyboard shortcut to permanently delete it. This way will bypass the Recycle Bin.
in Java, directory deletion is possible only for empty directory, which leads to methods like the following :
/**
* Force deletion of directory
* @param path
* @return
*/
static public boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
This one will delete your folder, even if non-empty, without troubles (excepted when this directory is locked by OS).
Why to invent a wheel with methods to delete recursively? Take a look at apache commons io. https://commons.apache.org/proper/commons-io/javadocs/api-1.4/
FileUtils.deleteDirectory(dir);
OR
FileUtils.forceDelete(dir);
That is all you need. There is also plenty of useful methods to manipulate files...
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