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));
}
那里getReasonForFileDeletionFailureInPlainEnglish(file)已经有很好的实施吗?否则我只需要自己写.
jar*_*bjo 24
在Java 6中,遗憾的是无法确定无法删除文件的原因.使用Java 7,您可以使用java.nio.file.Path#delete()它,如果无法删除文件或目录,它将为您提供失败的详细原因.
请注意,file.list()可能会返回目录的条目,这些条目可以删除.删除的API文档说明只能删除空目录,但如果包含的文件是例如特定于操作系统的元数据文件,则目录被视为空.
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.";
    }
}
xas*_*tor 10
请注意,它可以是您自己的应用程序,可以防止文件被删除!
如果您之前写过该文件并且未关闭编写器,则您自己锁定该文件.
也可以使用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);
}
由于一种或多种原因,删除可能会失败:
File#exists()测试)。所以每当删除失败时,做一个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 + ".");
}
| 归档时间: | 
 | 
| 查看次数: | 38705 次 | 
| 最近记录: |