Why does 'File.exists' return true, even though 'Files.exists' in the NIO 'Files' class returns false

时光总嘲笑我的痴心妄想 提交于 2019-11-29 03:33:35

As to why there may be a difference between the two, contrast their documentation:

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.

That could possibly explain the difference between the two, perhaps the Files one is having troubles ascertaining the existence of the file.

For example, under Linux, it's possible to set up directory and file permissions in such a way that you can open a file that exists but cannot see that it exists (by taking away read permission on the directory the file is in while leaving the file permissions more open).

As per more of Oracle's documentation, Files.exists() only returns true if the file is verified to exist.

A return value of false does not mean it doesn't exist.

They suggest you use both exists() and notExists() to cover the three possibilities, something like:

if (Files.exists(fspec)) {
    System.out.println("It exists!");
else if (Files.notExists(fspec)) {
    System.out.println("It does not exist!");
else
    System.out.println("I have no idea!");

That covers the three possibilities of file state covered in that link above:

  • The file is verified to exist.
  • The file is verified to not exist.
  • The file's status is unknown. This result can occur when the program does not have access to the file.
Иван Белозор

i had a same problem, but your hack doesn't helped me. When file was actually exist all methods returned me false:

Files.exists(path) = false, 
path.toFile().exists() = false, 
Files.notExists(path) = true, 
Files.exists(path) || path.toFile().exists() = false

But if at this moment in the explorer a network directory with this file was opened, then its existence was correctly handled

I solved this problem by creation of a new file in directory (then delete it):

Files.createFile(Paths.get(path.getParent().toString(), "test"));

After that command, apparently, Windows update information about folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!