Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path.startsWith returns false for a Windows file path on Linux

Tags:

java

linux

nio

Why would this be?

Path parent1 = Paths.get("/flugel/borf/noggin");
Path child1 = Paths.get("/flugel/borf/noggin/foo/bar/baz.jpg");
System.out.println("child1 startsWith parent1? " + child1.startsWith(parent1));
System.out.println(child1.getFileSystem());
System.out.println(parent1.getFileSystem());

Path parent2 = Paths.get("C:\\foo");
Path child2 = Paths.get("C:\\foo\\bar\\baz.jpg");
System.out.println("child2 startsWith parent2? " + child2.startsWith(parent2));
System.out.println(child2.getFileSystem());
System.out.println(parent2.getFileSystem());

returns

child1 startsWith parent1? true
sun.nio.fs.LinuxFileSystem@f5f2bb7
sun.nio.fs.LinuxFileSystem@f5f2bb7
child2 startsWith parent2? false
sun.nio.fs.LinuxFileSystem@f5f2bb7
sun.nio.fs.LinuxFileSystem@f5f2bb7

I'm running Java 8 on Ubuntu, but nothing about the javadocs for Path.startsWith explains why this occurs. Neither file path contains any actual files.

like image 203
ben3000 Avatar asked Oct 19 '22 11:10

ben3000


1 Answers

You have to check the code to see what is actually going on. So when you create a Path normalizeAndCheck function is called. In your case this is called on sun.nio.fs.UnixPath. Since path delimiter for *nix is / path strings will be normalized by /.

In case of Windows paths there are no / so they will stay exactly the same, so it will compare "C:\\foo" "C:\\foo\\bar\\baz.jpg" which are different strings and hence no common prefix.

like image 179
user987339 Avatar answered Oct 21 '22 05:10

user987339