我正在尝试确定网络文件夹中是否存在文件:
// File name is "\\QWERTY\folder\dir\A123456.TXT"
Path path = Paths.get("\\\\QWERTY\\folder\\dir\\A123456.TXT")
使用NIO文件:
Files.exists(path) == false
使用文件:
path.toFile().exists() == true
根据我们的测试,使用File似乎是正确的.为什么File比Files更好?
那么,这是什么?不能两者兼得!
但是等等,还有Files.notExists(路径).
当网络共享文件实际存在时
Files.exists(path): false
Files.notExists(path): false
path.toFile().exists(): true
当网络共享文件实际上不存在时
Files.exists(path): false
Files.notExists(path): true
path.toFile().exists(): false
另一种同样疯狂的方式来看上面的三个结果
boolean exists = Files.exists(path) || !Files.notExists(path)
boolean notExists = Files.notExists(path) || !Files.exists(path)
boolean oldFashionedExists = path.toFile().exists()
:smileyFace:
环境与评论
该程序在Windows 8.1 Pro 32位计算机(操作系统和计算机)上运行,并从Windows 2008 R2(32位)计算机检查网络共享.
为了确定Files.exists失败,我安装了一个WatchService来监视该文件夹,并在Files.exists检查时看到该文件确实存在.然后我记录了两个方法,发现File.exists是正确的.
现在,在我的代码中,我将检查为Files.exists(path)|| path.toFile().存在().
有点必须做两件事似乎很愚蠢.可能只是稍后逃脱.只是试图让工程师在甲骨文的怀疑中受益,但整个事情相当愚蠢,他们报告的不同.
另外,我不在乎“存在”是否立即过时.我只是想知道文件是否存在于我们正在检查的瞬间.我从未遇到过这种情况 – 我和我的另一位开发人员花了30个小时试图弄清楚为什么我们的程序因为这个’功能’而没有接口.
冥想这一段时间
File.exists(): Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.
Files.exists(): Returns true if the file exists; false if the file does not exist or its existence cannot be determined.
这让我感到震惊! “当且仅当此抽象路径名表示的文件或目录存在时;否则为false”与“如果文件存在则为”;如果文件不存在或者无法确定其存在,则为false
那么,如果“存在无法确定”,File.exists仍然可以成为现实吗?显然,存在可以(并且正在)由File确定,但不是由Files确定.