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

Introduction

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.

Demo

import java.io.IOException;
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\Main.java file exists
    Path p1 = Paths.get("C:\\myData\\Main.java");
    Path p2 = Paths.get("C:\\myData\\..\\myData\\Main.java");

    // 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) {
      e.printStackTrace();
    }
  }
}

Result

Related Topic