Converting Relative Paths to Absolute Paths

前端 未结 9 1291
北荒
北荒 2020-12-05 04:14

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

9条回答
  •  广开言路
    2020-12-05 05:03

    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.

提交回复
热议问题