Path Relativize And Resolve Roundtrip

Derive the relative path between two locations with relativize and anchor it back with resolve; mixing absolute and relative inputs throws.

JavaData Integrity

Code

snippet
import java.nio.file.Path;

public class DeployPaths {

    public static void main(String[] args) {
        Path projectRoot = Path.of("/srv/app");
        Path config = Path.of("/srv/app/config/logging.yml");
        Path target = Path.of("/srv/releases");

        // relativize:从 config 走到 target 需要逐级回溯的相对段
        Path configToTarget = config.relativize(target);
        System.out.println("config -> target: " + configToTarget);

        // resolve 再锚回绝对位置:往返 roundtrip 回到 target
        Path roundtrip = config.resolve(configToTarget).normalize();
        System.out.println("roundtrip equals target: " + roundtrip.equals(target));

        // 同根兄弟目录得到 ../ 形态
        System.out.println("root -> target: " + projectRoot.relativize(target));

        // 一边绝对一边相对:IllegalArgumentException,而不是默默给出错误结果
        try {
            Path.of("config").relativize(target);
        } catch (IllegalArgumentException mixed) {
            System.out.println("mixed absolute/relative -> " + mixed.getMessage());
        }
    }
}

What the code does

Path Relativize And Resolve Roundtrip keeps everything in the class DeployPaths and the function main.

Applying it

Running the file prints labeled results such as config -> target:, roundtrip equals target:, root -> target: — each operation’s effect is visible in the output.

Statements that matter

Path roundtrip = config.resolve(configToTarget).normalize();
Path config = Path.of("/srv/app/config/logging.yml");
Path configToTarget = config.relativize(target);

Interactive Tools for This Topic

FAQ

What does Path Relativize And Resolve Roundtrip print when run?
The script runs standalone; its 4 labeled outputs include `config -> target:`, `roundtrip equals target:`, `root -> target:`.