如何判断为什么在 Java 中文件删除失败? [英] How to tell why a file deletion fails in Java?

查看:27
本文介绍了如何判断为什么在 Java 中文件删除失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

getReasonForFileDeletionFailureInPlainEnglish(file) 有没有很好的实现?否则我就只能自己写了.

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

推荐答案

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

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.

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

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.

这篇关于如何判断为什么在 Java 中文件删除失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆