[英]Path.startsWith returns false for a Windows file path on Linux
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. 我在Ubuntu上运行Java 8,但没有关于
Path.startsWith
的javadoc解释为什么会发生这种情况。 Neither file path contains any actual files. 两个文件路径都不包含任何实际文件。
I think below line from Java Docs of java.nio.file.Path answers your question 我想java.nio.file.Path的 Java Docs下面的行回答了你的问题
An object that may be used to locate a file in a file system.
可用于在文件系统中查找文件的对象。 It will typically represent a system dependent file path .
它通常表示系统相关的文件路径 。
You have to check the code to see what is actually going on. 您必须检查代码以查看实际发生的情况。 So when you create a Path normalizeAndCheck function is called.
因此,当您创建Path时,会调用normalizeAndCheck函数。 In your case this is called on
sun.nio.fs.UnixPath
. 在你的情况下,这是在
sun.nio.fs.UnixPath
上sun.nio.fs.UnixPath
。 Since path delimiter for *nix is /
path strings will be normalized by /
. 由于* nix的路径分隔符是
/
path字符串将由/
标准化。
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. 在Windows路径的情况下,没有
/
它们将保持完全相同,因此它将比较"C:\\\\foo"
"C:\\\\foo\\\\bar\\\\baz.jpg"
这是不同的字符串,因此没有共同前缀。
As described in the Javadocs, Java uses the "path separator" to determines the current operating environment path separator character. 如Javadocs中所述,Java使用“路径分隔符”来确定当前操作环境路径分隔符的字符。 This can be accessed via:
这可以通过以下方式访问:
System.getProperty("path.separator");
on UNIX based system it is "/", while on Windows systems it is "\\". 在基于UNIX的系统上它是“/”,而在Windows系统上它是“\\”。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.