views:

758

answers:

2

Hi,

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!

+1  A: 

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:

public boolean isAbsolute(File f) 
{
        int pl = f.getPrefixLength();
        return (((pl == 2) && (f.getPath().charAt(0) == slash))
                || (pl == 3));
}

UnixFileSystem:

public boolean isAbsolute(File f) 
{
        return (f.getPrefixLength() != 0);
}
Kevin Montrose
A: 

I guess you are looking for File.isAbsolute()

http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#isAbsolute()

Thorbjørn Ravn Andersen