Cannot delete folder using Java
Solution 1
You could be getting a failed delete for a number of reasons; the file could be locked by the file system, you may lack permissions, or could be open by another process etc.
If you're using Java 7 or above you can use the javax.nio.*
API; it's a little more reliable & consistent than the legacy java.io.File
classes:
Path fp = file.toPath();
Files.delete(fp);
If you want to catch the possible exceptions:
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
Check the docs for more info on IO in Java 7
Solution 2
As you aren't checking the return value of delete(), the output you produce is meaningless. The deletion could have failed for any number of reasons:
- the file is a non-empty directory
- the file is open by another user (on some platforms)
- you don't have permission to delete that file.
Solution 3
Try this code
public class DeleteDirTest {
public static void main(String[] args) throws IOException {
DeleteDirTest test = new DeleteDirTest();
boolean result = test.deleteDir(new File("D:/test"));
System.out.println(result);
}
public boolean deleteDir(File file) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(file, children[i]));
if (!success) {
return false;
}
}
}
return file.delete();
}
}
TV Nath
I am a moderate Software Engineer who likes to improve my knowledge in technologies related Java, J2EE, and Javascript. There are a lot of space for me to improve.
Updated on June 26, 2022Comments
-
TV Nath almost 2 years
I am trying to delete a folder which has only files but no sub folders without success.
Code:
File rowFolder = new File(folderPath); String[] files = rowFolder.list(); for (String file : files){ File deleteFile = new File(file); System.out.println("deleting file -"+deleteFile.getName()); deleteFile.delete(); } System.out.println("deleting folder -"+rowFolder.getName()); rowFolder.delete();
Output:
deleting file -testing.pdf deleting file -app_json.json deleting file -photo.jpg deleting folder -bundle_folder
The code doesn't delete any folder nor any file. Why is that?