Java - Use Files.isSameFile(Path p1, Path p2) to check if two paths refer to the same file.


If p1.equals(p2) returns true, this method returns true without verifying the existence of the paths in the file system.

Otherwise, it checks with the file system, if both paths locate the same file.

The isSameFile()throws an IOException when an I/O error occurs.

The following code demonstrates how the isSameFile() method works.


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    // Assume that C:\myData\ file exists
    Path p1 = Paths.get("C:\\myData\\");
    Path p2 = Paths.get("C:\\myData\\..\\myData\\");

    // Assume that C:\abc.txt file does not exist
    Path p3 = Paths.get("C:\\abc.txt");
    Path p4 = Paths.get("C:\\abc.txt");
    try {//from  ww w . ja  v  a  2s .com
      boolean isSame = Files.isSameFile(p1, p2);
      System.out.println("p1 and p2 are the same: " + isSame);

      isSame = Files.isSameFile(p3, p4);
      System.out.println("p3 and p4 are the same: " + isSame);
    } catch (IOException e) {


Related Topic