3

Why does this code return false?

Path path = Paths.get("C:\\aaa\\bbb\\ccc");
Files.exists(path); // false!?

Even when I convert to it from a File (which exists):

File file = new File("C:\\aaa\\bbb\\ccc");
file.exists(); // true!!!
Path path = file.toPath();
Files.exists(path); // still false!?
sikidhart
  • 401
  • 4
  • 16
  • 1
    Does `Files.size(path);` throw an exception? If it does, does that exception contain a meaningful message? – VGR Jul 31 '19 at 02:08
  • This works OK for me – Scary Wombat Jul 31 '19 at 02:09
  • 1
    `mkdir -p /mnt/c/aaa/bbb` `touch /mnt/c/aaa/bbb/ccc` `File file = new File("C:\\aaa\\bbb\\ccc"); System.out.println(file.exists()); // true Path path = file.toPath(); System.out.println(Files.exists(path)); // true` – Scary Wombat Jul 31 '19 at 02:10
  • 1
    Is `C:\aaa\bbb\ccc` a symbolic link? What are the permissions on the file? Please create a [mcve] that demonstrates this issue and verify that this still happens if there's no other code around this. Post the complete code for the [mcve]. – Jim Garrison Jul 31 '19 at 03:17
  • my mistake. I was using Iterator iterator = path.iterator(); to try to get the files in the directory and recursively calling my method. we can probably delete this post. sorry. [Jim Garrison's answer might be useful for some people though] – sikidhart Jul 31 '19 at 04:05

1 Answers1

5

I was able to reproduce this under the following specific circumstances:

  1. The OS is Windows (implied by the path syntax)
  2. The path refers to a directory
  3. The directory is read-only or, the user does not have "List Folder Contents" permission.

I tested this on Linux (Centos 6) and cannot reproduce it even when changing the filemode on the directory (i.e. chmod -x /aaa/bbb/ccc or chmod -r /aaa/bbb/ccc)

So this appears to occur only on Windows. There must be some difference between how java.io and java.nio.file implement existence testing with regards to file permissions on Windows.

Check the permissions on the directory.

This may be a bug worth reporting.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • the problem was caused by my mistake. but to confirm, yeah, Windows, read-only directory. I'm not sure about how to change the "List Folder Contents" permissions. Thanks for investigating. upvoted. – sikidhart Jul 31 '19 at 04:10
  • Curiously on Linux with a read-only directory all the calls return `true` as expected. – Jim Garrison Jul 31 '19 at 04:33