← 中文资源

简体中文版本

Path 的 relativize 与 resolve 往返

relativize 算出从一个路径走到另一个的相对段,resolve 再锚回绝对位置完成往返;一边绝对一边相对会直接抛 IllegalArgumentException。

阅读英文原文

实现说明

除了类 DeployPaths和函数 main,文件里再无其他定义。

使用要点

  • 跑完文件,输出里会留下标记——config -> target:、roundtrip equals target:、root -> target:。

常见问题

运行「Path 的 relativize 与 resolve 往返」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 config -> target:、roundtrip equals target:、root -> target: 标签标明各步骤。

核心语句

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

代码示例

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());
        }
    }
}