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

前端 未结 4 783
臣服心动
臣服心动 2021-02-14 03:50

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?

4条回答
  •  难免孤独
    2021-02-14 04:21

    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.

提交回复
热议问题