有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java 7中的io,如何通过一个实际示例演示文件之间的差异。存在和文件。不存在?

Files.notExists的文档中:

This method is intended for cases where it is required to take action when it can be confirmed that a file does not exist..........Note that this method is not the complement of the exists method. Where it is not possible to determine if a file exists or not then both methods return false.

理论上的差异是可以理解的。可以是File.exists()返回false,但这并不一定意味着文件不存在。Java7为我们提供了处理这种情况的Files.notExists()方法

我尝试在Windows 7上创建一个文件,并拒绝对它的所有权限(包括管理权限)。但这并没有产生File.exists()返回false的行为。有人能帮忙吗


共 (1) 个答案

  1. # 1 楼答案

    以下代码将起作用。在您遇到拒绝权限问题的情况下,您可以检查操作系统安装分区中的文件夹。(C:\)。下面的方法会奏效

       Path path = Paths.get("D:\\TestFolder");
        if (Files.exists(path)) {
            System.out.println("exist");
        }
        if (Files.notExists(path)) {
            System.out.println("not exist");
        }
    

    javadoc表示Files.notExists()

    Tests whether the file located by this path does not exist. This method is intended for cases where it is required to take action when it can be confirmed that a file does not exist. Note that this method is not the complement of the exists method. Where it is not possible to determine if a file exists or not then both methods return false. As with the exists method, the result of this method is immediately outdated. If this method indicates the file does exist then there is no guarantee that a subsequence attempt to create the file will succeed. Care should be taken when using this method in security sensitive applications.