Search code examples
javafileniojava-io

Can I get sameFile is true after copy in Java nio?


I thought the result is true when Files.isSameFile invoke after fileB is copied from fileA, because fileA is same with fileB. However, the result is false.

Path pathA = Path.of("A.txt");
Path pathB = Path.of("B.txt");

Files.copy(pathA, pathB);

if(Files.isSameFile(pathA, pathB))
    System.out.println("file is same"); 
else
    System.out.println("file is not same"); // the result

I found that Files.isSameFile compare only String of Path.

How can I get true after copy? I want

Path pathA = Path.of("A.txt");
Path pathB = Path.of("B.txt");

Files.copy(pathA, pathB);

if(??) <-- I want
    System.out.println("file is same"); 

Solution

  • The API call you need is Files.mismatch(Path,Path) which returns -1 when the byte comparison of two files is same.

    boolean identical = Files.mismatch(pathA, pathB) == -1;
    

    As covered in other comments, Files.isSameFile deals with cases where two paths that are different could refer to the same underlying file on the filesystem. For example if I have directory "build" and file "build.xml":

    Path a = Path.of("build.xml");
    Path b = Path.of("build/../build.xml");
    
    Files.isSameFile(a,b)
    ==> true
    a.equals(b)
    ==> false
    

    It's also worth noting that - in JDK17 source code - the first step of Files.mismatch is if (Files.isSameFile(a,b)) { return -1; }; which may avoid the need to open files for byte-wise comparison.