对于Linux上的Windows文件路径,Path.startsWith返回false [英] Path.startsWith returns false for a Windows file path on Linux
问题描述
为什么会这样?
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());
返回
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
我在Ubuntu上运行Java 8,但是关于Path.startsWith
的javadocs的任何内容都没有解释为什么会发生这种情况.这两个文件路径均不包含任何实际文件.
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.
推荐答案
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 /
.
对于Windows路径,没有/
,因此它们将保持完全相同,因此它将比较"C:\\foo"
"C:\\foo\\bar\\baz.jpg"
,它们是不同的字符串,因此没有公共前缀.
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.
这篇关于对于Linux上的Windows文件路径,Path.startsWith返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!