'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 1:[1]

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)));

Solution 2:[2]

/ is the path separator on Unix and Unix-like systems like Linux. Modern Windows operating systems can use both \ and / as path separator.

Solution 3:[3]

If you develop for Windows and Linux you can generally use / as a path separator and don't bother using File.separator. For example Java on Windows resolves all these pathnames correctly without "\\" in a String, even UNC format:

var unc =  Path.of("//storage/media/camera");
// ==> \\storage\media\camera
var mdrive = Path.of("M:/camera");
// ==> M:\camera
var build = Path.of("build/classes");
// ==> build\classes
var a= Path.of("/Temp");
// ==> \Temp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 anmatika
Solution 3