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

前端 未结 4 780
臣服心动
臣服心动 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:14

    java.nio.file.Files.isSameFile() checks if two filepaths refers to the same file = i.e. both are hardlinks (this is portable for all OS and filesystems (yeah)). This method traverse symbolic links too then you can compare two symbolic links to filenames points to the same inode on unix filesystem/Windows NTFS.

    You can locate (not editable) file duplicates (this same size and content), determines if are soft/hard links then if not - you can save pathname and delete first then create link to second. You can save 50% disk space.

    0 讨论(0)
  • 2021-02-14 04:20
    • if equal() == true then isSameFile() == true
    • if isSameFile() == true, equal() is not always true

    The isSameFile() method first checks if the Path objects are equal in terms of equal(), and if so, it automatically returns true without checking to see if either file exists.

    If the Path object equals() comparison returns false, then it locates each file to which the path refers in the file system and determines if they are the same, throwing a checked IOException if either file does not exist.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-14 04:27

    isSameFile is from java.nio.file.Files and Path.equals is from java.nio.file.Path

    isSameFile --> Tests if two paths locate the same file. ie) checks two Path objects are for the same file equals --> Tests this path for equality with the given object.

    0 讨论(0)
提交回复
热议问题