Search code examples
javafilepathrelative-path

Apply relative path to a given path in Java


Given an absolute path to a directory: pathA, and a relative path pathB, find the absolute path of pathB from pathA.

public String applyPath(String pathA, String pathB) { ...

assertEquals("/a/b/file.txt", applyPath("/a/b/c/d", "../../file.txt"));

assertEquals("/a/b/c/file.txt", applyPath("/a/b/c", "./file.txt"));

How would i write such a function using java libraries preferably and not do string manipulation.


Solution

  • You should use Java Paths and it's resolve method like

    Paths.get(pathA).resolve(pathB);