Reputation: 4989
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.
Upvotes: 5
Views: 1650
Reputation: 6126
As described in the Javadocs, Java uses the "path separator" to determines the current operating environment path separator character. This can be accessed via:
System.getProperty("path.separator");
on UNIX based system it is "/", while on Windows systems it is "\". If you want to change these properties you can use the following to achieve that:
Properties p = System.getProperties();
p.put("path.separator", "\\");
System.setProperties(p);
Upvotes: 0
Reputation: 10707
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.
Upvotes: 2
Reputation: 9946
I think below line from Java Docs of java.nio.file.Path answers your question
An object that may be used to locate a file in a file system. It will typically represent a system dependent file path.
Upvotes: 1