English 中文(简体)
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.

问题回答

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.

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.";
    }
}

Be aware that it can be your own application that prevents a file from being deleted!

If you wrote to the file previously and didn t close the writer, you are locking the file yourself.

Java 7 java.nio.file.Files class can be also used:

http://docs.oracle.com/javase/tutorial/essential/io/delete.html

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

A deletion may fail due to one or more reasons:

  1. File does not exist (use File#exists() to test).
  2. File is locked (because it is opened by another app (or your own code!).
  3. You are not authorized (but that would have thrown a SecurityException, not returned false!).

So whenever deletion fails, do a File#exists() to check if it is caused by 1) or 2).

Summarized:

if (!file.delete()) {
    String message = file.exists() ? "is in use by another app" : "does not exist";
    throw new IOException("Cannot delete file, because file " + message + ".");
}

As pointed out in File.delete()

you may use a SecurityManager that throws the exeception for you.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签