I have an absolute path to file A.
I have a relative path to file B from file A\'s directory. This path may and will use \"..\" to go up the directory structure in
What's better than just creating a utility that converts relative paths to absolute paths is to create a utility that converts any path passed to it into an absolute path so that you don't have to check on the client-side.
The below code works for me in both cases and I've used the String type at the signature of the method (both parameter and return value):
public static String toAbsolutePath(String maybeRelative) {
Path path = Paths.get(maybeRelative);
Path effectivePath = path;
if (!path.isAbsolute()) {
Path base = Paths.get("");
effectivePath = base.resolve(path).toAbsolutePath();
}
return effectivePath.normalize().toString();
}
Changing the above code to expose Path types on the signature of the method is trivial (and actually easier) but I think that using String on the signature gives more flexibility.