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.
Code
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
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.