Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell why a file deletion fails in Java?

File file = new File(path); if (!file.delete()) {     throw new IOException(         "Failed to delete the file because: " +         getReasonForFileDeletionFailureInPlainEnglish(file)); } 

Is there a good implementation of getReasonForFileDeletionFailureInPlainEnglish(file) already out there? Or else I'll just have to write it myself.

like image 737
Arne Evertsson Avatar asked Nov 13 '09 12:11

Arne Evertsson


People also ask

How do you delete a file that is used by another process in Java?

Method available in every Java versionFile filePath = new File( "SomeFileToDelete. txt" ); boolean success = filePath. delete();

How do I delete a specific file in a directory in Java?

In Java, we can delete a file by using the File. delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname. If the pathname is a directory, that directory must be empty to delete.


2 Answers

In Java 6, there is unfortunately no way to determine why a file cannot be deleted. With Java 7, you can use java.nio.file.Files#delete() instead, which will give you a detailed cause of the failure, if the file or directory cannot be deleted.

Note that file.list() may return entries for directories, which can be deleted. The API documentation for delete says that only empty directories can be deleted, but a directory is considered empty, if the contained files are e.g. OS specific metadata files.

like image 154
jarnbjo Avatar answered Oct 05 '22 22:10

jarnbjo


Hmm, best I could do:

public String getReasonForFileDeletionFailureInPlainEnglish(File file) {     try {         if (!file.exists())             return "It doesn't exist in the first place.";         else if (file.isDirectory() && file.list().length > 0)             return "It's a directory and it's not empty.";         else             return "Somebody else has it open, we don't have write permissions, or somebody stole my disk.";     } catch (SecurityException e) {         return "We're sandboxed and don't have filesystem access.";     } } 
like image 40
Cory Petosky Avatar answered Oct 06 '22 00:10

Cory Petosky