Question

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!

Was it helpful?

Solution

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);
}

OTHER TIPS

In Java 7:

new File(path).isAbsolute()

My crack at this using Apache FilenameUtil -

   public static boolean isAbsolute(final String path) {
      return FilenameUtils.getPrefixLength(path) != 0;
   }

Technically this is returning !relative. Which is fine for my purposes.

I ended up using this (in Java 6):

private static boolean testPath(String path) {
    int prefixLen = FilenameUtils.getPrefixLength(path);
    if (testPathWin(path, prefixLen) || testPathLinux(prefixLen))
        return true;
    else
        return false;
}

private static boolean testPathWin(String path, int prefixLen) {
    if (prefixLen == 3)
        return true;
    File f = new File(path);
    if ((prefixLen == 2) && (f.getPath().charAt(0) == '/'))
        return true;
    return false;
}

private static boolean testPathLinux(int prefixLen) {
    return (prefixLen != 0);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top