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!
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: