Java I/O How to - Determine whether two paths are equivalent with equals method








Question

We would like to know how to determine whether two paths are equivalent with equals method.

Answer

import java.nio.file.Path;
import java.nio.file.Paths;
/*from w  w  w  .  j av  a2s. com*/
public class Main {
  public static void main(String[] args) {
    Path path1 = Paths.get("/home/docs/users.txt");
    Path path2 = Paths.get("/home/docs/users.txt");
    Path path3 = Paths.get("/home/music/A.mp3");

    testEquals(path1, path2);
    testEquals(path1, path3);
  }
  private static void testEquals(Path path1, Path path2) {
    if (path1.equals(path2)) {
      System.out.println("equal");
    } else {
      System.out.println("NOT equal");
    }
  }
}

The code above generates the following result.