gpt4 book ai didi

java - Files.notExists 在网络目录中始终为 false

转载 作者:行者123 更新时间:2023-11-29 04:47:02 25 4
gpt4 key购买 nike

我正在尝试使用 Files.notExists 方法检查文件夹是否不存在。它适用于我的计算机 (Windows) 中的本地资源,但当我指向共享资源时,它总是返回 false。情况如下:

检查本地资源是否存在:

String stringPath = "C:/existentFolder";
Path path = Paths.get(stringPath);
Files.notExists(path) // false
//OK, because the folder exists

String stringPath = "C:/nonExistentFolder";
Path path = Paths.get(stringPath);
Files.notExists(path) // true
//OK, because the folder doesn't exists

检查共享资源是否存在:

String stringPath = "\\sharedResourceName\existentFolder";
Path path = Paths.get(stringPath);
Files.notExists(path) // false
//OK, because the folder exists

String stringPath = "\\sharedResourceName\nonExistentFolder";
Path path = Paths.get(stringPath);
Files.notExists(path) // false
//Why here it evaluates to false if it is indeed a non existent folder??

最佳答案

documentation of Files.notExists()状态:

Returns: true if the file does not exist; false if the file exists or its existence cannot be determined

我假设无法使用 File/Files 类访问未映射的网络共享,因此结果无法确定(因此为假)。

以下代码使用 Oracle Java 8 按预期工作:

    String s = "\\\\myserver\\sharename\\directory";
Path p = FileSystems.getDefault().getPath(s);
System.out.println(Files.notExists(p, LinkOption.NOFOLLOW_LINKS));
System.out.println(!new File(s).exists());

如果路径正确,它输出两次 false,如果它存在,则输出 true。您是否检查过 Windows 资源管理器中是否可以访问网络共享?

顺便说一句:使用的网络资源名称是错误的。在 Java 中,您必须转义反斜杠,因此访问网络共享的代码中正确的字符串(如果可以的话)将是 \\\\sharedResourceName\\existentFolder

关于java - Files.notExists 在网络目录中始终为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36742253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com