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

前端 未结 2 1191
野趣味
野趣味 2020-12-09 17:49

I am trying to determine if a file exists in a network folder:

// File name is "\\\\QWERTY\\folder\\dir\\A123456.TXT"
Path path = Paths.get("\\         


        
相关标签:
2条回答
  • 2020-12-09 18:16

    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

    0 讨论(0)
  • 2020-12-09 18:28

    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.
    0 讨论(0)
提交回复
热议问题