How about File.isAbsolute():
File file = new File(path);
if (file.isAbsolute()) {
...
}
Answer from Jon Skeet on Stack OverflowVideos
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);
}
In Java 7:
new File(path).isAbsolute()
Try with this:
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws IOException {
Path path = Paths.get("myFile.txt");
Path absolutePath = path.toAbsolutePath();
System.out.println(absolutePath.toString());
}
}
You can use:
Path absolutePath = path.toAbsolutePath().normalize();
... at least to eliminate the redundant relative sections. As the documentation for normalize() mentions, in case that an eliminated node of the path was actually a link, then the resolved file may be different, or no longer be resolvable.
If I get your problem right, you could do something like this:
File a = new File("/some/abs/path");
File parentFolder = new File(a.getParent());
File b = new File(parentFolder, "../some/relative/path");
String absolute = b.getCanonicalPath(); // may throw IOException
String absolutePath = FileSystems.getDefault().getPath(mayBeRelativePath).normalize().toAbsolutePath().toString();