Search code examples
javapathoperating-systemequalsenvironment

Path.equals behaves different on Windows and Linux


I use the following code to compare two Paths in Java:

import java.nio.file.Paths;

public class PathTest {
   public static void main(String args[]) {
      String path1 = "path1\\file1.jpg";
      String path2 = "path1/file1.jpg";
      System.out.println(Paths.get(path1));
      System.out.println(Paths.get(path2));
      System.out.println(Paths.get(path1).equals(Paths.get(path2)));
   }
}

I do get the following output on my Windows machine:

path1\file1.jpg
path1\file1.jpg
true

And on linux:

path1\file1.jpg
path1/file1.jpg
false

What's going on here?


Solution

  • Path separator is different for Windows and Linux.

    For Windows is \

    For Linux is /

    Safe way in java of building paths that work on both evironments is

    Path filePath = Paths.get("path1", "path2");
    

    In your case you use a String to form a Path. So in Windows

     String path2 = "path1/file1.jpg";
     Paths.get(path2)  -> results in "path1\file1.jpg"
    

    It converts the separator / to a windows separator \

    After that conversion both path1 and path2 are the same

    Now when you run in Linux the following code

          String path1 = "path1\\file1.jpg"; -> this will not be ok for linux and also will not try to convert it to / as the first \ is an escape character
          String path2 = "path1/file1.jpg";  -> this will be ok for linux /
          System.out.println(Paths.get(path1));
          System.out.println(Paths.get(path2));
          System.out.println(Paths.get(path1).equals(Paths.get(path2)));