Search code examples
javajava-7nio

Java NIO - How is Files.isSameFile different from Path.equals


I could not understand how java.nio.file.Files.isSameFile method is different from java.nio.file.Path.equals method.

Could anybody please tell how they are different?


Solution

  • They are very different.

    For instance:

    final Path p1 = Paths.get("/usr/src");
    final Path p2 = Paths.get("/usr/../usr/src");
    
    p1.equals(p2); // FALSE
    Files.isSameFile(p1, p2); // true
    
    final Path p1 = fs1.getPath("/usr/src");
    final Path p2 = fs2.getPath("/usr/src");
    
    p1.equals(p2); // FALSE
    

    A Path is equal to another Path if and only if:

    • they have the same FileSystem;
    • they have the same root element;
    • they have the same name elements.

    This is very different from Files.isSameFile() which accesses the filesystem and tries and see if two Paths point to the same filesystem resource.