如何从两个绝对路径(或 URL)构造 Java 中的相对路径? [英] How to construct a relative path in Java from two absolute paths (or URLs)?

查看:20
本文介绍了如何从两个绝对路径(或 URL)构造 Java 中的相对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个绝对路径,例如

Given two absolute paths, e.g.

/var/data/stuff/xyz.dat
/var/data

如何创建以第二条路径为基础的相对路径?在上面的例子中,结果应该是:./stuff/xyz.dat

How can one create a relative path that uses the second path as its base? In the example above, the result should be: ./stuff/xyz.dat

推荐答案

这有点绕,但为什么不使用 URI?它有一个相对化方法,可以为你做所有必要的检查.

It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you.

String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "stuff/xyz.dat"

请注意,对于文件路径,从 Java 1.7 开始就有 java.nio.file.Path#relativize,正如 @Jirka Meluzin另一个答案中.

Please note that for file path there's java.nio.file.Path#relativize since Java 1.7, as pointed out by @Jirka Meluzin in the other answer.

这篇关于如何从两个绝对路径(或 URL)构造 Java 中的相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆