能够在没有权限的情况下删除文件

Able to delete a file without permissions

尽管 Tomcat 用户没有删除权限,但为什么我可以在我的 Java 代码中删除文件?

我的服务器是运行以下代码,删除并重新创建一个文件(如果存在):

File fileCSV = new File(filePath);
    try {
        if (fileCSV.exists()) {
            fileCSV.delete();
        }
        fileCSV.createNewFile();
    } catch (IOException ex) {
        throw new FooImportException("Error creating new file");
    }

尽管服务器使用的用户没有删除权限 - 只有读写权限,但它能够删除文件。

我确定这些是相关权限,因为代码在没有 "Create files / Write data" 权限的文件创建行上失败。然而,它不会在缺少 "Delete" 权限时在删除行上失败 这可能是什么原因?

根据 JavaDocs for File#delete

public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

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.

Returns:
true if and only if the file or directory is successfully deleted; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file

因此,File#delete 实际上不会在无法删除文件时抛出 Exception,而是 returns 基于删除成功抛出 boolean操作。

如果 Exception 对您很重要,那么您应该改用 Files#delete

重要的是要注意——这只解决了基于可用代码的"why does it not fail"问题,而不是基于可用文件权限"would it fail"的问题