Java:无论操作系统如何,如何确定路径是否是绝对的
不管程序当前运行的平台如何,Java 中是否有办法找出给定路径是否是绝对路径。 所以,我想要的可能是像下面的例子:
在Linux上:
new File("/home/").isAbsolute() // Should return true.
new File("C:/My Documents").isAbsolute() // Should *also* return true.
在Windows上:
new File("C:/Documents").isAbsolute() // Should return true.
new File("/home/").isAbsolute() // Should *also* return true.
我可能可以编写一些代码来解决这个问题,但我只是想知道是否有人知道Java中提供的内置类来解决这个问题这个问题。 或者有人遇到过这个问题吗? 你是怎么解决的?
谢谢!
Is there anyway in Java to find out if the given path is absolute or not regardless of the platform the program is currently running. So, what I want is probably something like the following example:
On Linux:
new File("/home/").isAbsolute() // Should return true.
new File("C:/My Documents").isAbsolute() // Should *also* return true.
On Windows:
new File("C:/Documents").isAbsolute() // Should return true.
new File("/home/").isAbsolute() // Should *also* return true.
I can probably code something to get around with this, but I just wanted to find out if anyone knew a built-in class provided in Java to solve this problem. Or has anyone ever come this problem? And how did you solve it?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有。
有一些底层 FileSystem 类(这是 Java 7,但它们早于也)暴露了 isAbsolute(),但它们不是公开的 - 所以你不应该使用它们,即使你这样做了,你的代码也会充满反射垃圾 - 并且只有“正确的”操作系统包含在 JRE 中,因此无论如何您都必须围绕它们进行编码。
以下是 isAbsolute(...) 的 Java 7 实现,可帮助您入门。 请注意,File.getPrefixLength() 是包私有的。
Win32FileSystem:
UnixFileSystem:
Nope.
There are some underlying FileSystem classes (that's Java 7, but they exist prior to it as well) that expose isAbsolute(), but they're not public - so you shouldn't use them, and even if you did your code would be full of reflection junk - and only the "correct" OS ones are included in the JRE, so you'd have to code around them anyway.
Here are the Java 7 implementations of isAbsolute(...) to get you started. Note that File.getPrefixLength() is package-private.
Win32FileSystem:
UnixFileSystem:
在 Java 7 中:
In Java 7:
我使用 Apache FilenameUtil 对此进行了破解 -
从技术上讲,这是返回 !relative。 这对我的目的来说很好。
My crack at this using Apache FilenameUtil -
Technically this is returning !relative. Which is fine for my purposes.
我最终使用了这个(在 Java 6 中):
I ended up using this (in Java 6):