编程语言
首页 > 编程语言> > Java File.delete()不会删除所有文件

Java File.delete()不会删除所有文件

作者:互联网

我有以下Java代码,它遍历目录中的所有文件并删除它们.

for(File file : tmpDir.listFiles())
{
    file.delete();
}

但它不会删除所有文件.当我这样做时,一些,通常是20到30,中有几千.是否有可能解决这个问题,或者我偶然发现了一些最好独自留下的Java巫毒?

解决方法:

它返回一个布尔值,你应该检查一下.从JavaDoc

Returns:
true if and only if the file or directory is successfully deleted; false otherwise

您应该检查退货的价值并采取行动.

如果它返回false,则可能是您没有删除该文件的权限.

在这种情况下,您可以检查文件是否可由应用程序写入,如果不尝试使其可写 – 再次返回一个布尔值.如果成功,您可以再次尝试删除.

您可以使用实用程序方法:

private void deleteFile(final File f) throws IOException {
    if (f.delete()) {
        return;
    }
    if (!f.canWrite() && !f.setWritable(true)) {
        throw new IOException("No write permissions on file '" + f + "' and cannot set writeable.");
    }
    if (!f.delete()) {
        throw new IOException("Failed to delete file '" + f + "' even after setting writeable; file may be locked.");
    }
}

我也会在JavaDoc中接受他们的建议:

Note that the Files class defines the delete method to throw an
IOException when a file cannot be deleted. This is useful for error
reporting and to diagnose why a file cannot be deleted.

前提是您使用的是Java 7.该方法抛出了许多可以处理的异常:

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

例子来自Oracle tutorial page.

标签:java,delete-file
来源: https://codeday.me/bug/20190714/1460047.html