如何判断Java中文件删除失败的原因?

Arn*_*son 37 java error-handling file-io jdk1.6 jdk6

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

那里getReasonForFileDeletionFailureInPlainEnglish(file)已经有很好的实施吗?否则我只需要自己写.

jar*_*bjo 24

在Java 6中,遗憾的是无法确定无法删除文件的原因.使用Java 7,您可以使用java.nio.file.Path#delete()它,如果无法删除文件或目录,它将为您提供失败的详细原因.

请注意,file.list()可能会返回目录的条目,这些条目可以删除.删除的API文档说明只能删除空目录,但如果包含的文件是例如特定于操作系统的元数据文件,则目录被视为空.

  • Java 7 API中似乎不存在此删除方法.[链接](http://download.oracle.com/javase/7/docs/api/java/nio/file/Path.html)编辑:刚刚发现它现在在Files类中.[链接](http://download.oracle.com/javase/7/docs/api/java/nio/file/Files.html) (9认同)

Cor*_*sky 21

嗯,我能做的最好:

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.";
    }
}
Run Code Online (Sandbox Code Playgroud)


xas*_*tor 10

请注意,它可以是您自己的应用程序,可以防止文件被删除!

如果您之前写过该文件并且未关闭编写器,则您自己锁定该文件.

  • 使用Java 6在Windows 7上进行测试时,我也遇到了这个问题.我在关闭阅读器之前尝试删除该文件但失败了. (2认同)

Qua*_*ark 9

也可以使用Java 7 java.nio.file.Files类:

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);
}
Run Code Online (Sandbox Code Playgroud)


Bal*_*usC 5

由于一种或多种原因,删除可能会失败:

  1. 文件不存在(用于File#exists()测试)。
  2. 文件被锁定(因为它被另一个应用程序(或您自己的代码!)打开。
  3. 您未获得授权(但这会引发 SecurityException,而不是返回 false!)。

所以每当删除失败时,做一个File#exists()检查它是由 1) 或 2) 引起的。

总结:

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 + ".");
}
Run Code Online (Sandbox Code Playgroud)


ba_*_*end -1

正如File.delete()中指出的

您可以使用 SecurityManager 为您抛出异常。