从绝对路径中提取相对路径

3
这似乎是一个简单的问题,但我很难用简洁的方式解决它。我有一个文件路径如下:
/this/is/an/absolute/path/to/the/location/of/my/file 我需要提取上述路径中的/of/my/file,因为这是我的相对路径。
我考虑的方法如下:
String absolutePath = "/this/is/an/absolute/path/to/the/location/of/my/file";
String[] tokenizedPaths = absolutePath.split("/");
int strLength = tokenizedPaths.length;
String myRelativePathStructure = (new StringBuffer()).append(tokenizedPaths[strLength-3]).append("/").append(tokenizedPaths[strLength-2]).append("/").append(tokenizedPaths[strLength-1]).toString();

这可能能够满足我的即时需求,但有人能否建议一种更好的方法来从Java提供的路径中提取子路径?谢谢。

你必须要知道根路径的样子或者“子”路径的样子。 - Kiril
2个回答

11

使用URI类:

URI base = URI.create("/this/is/an/absolute/path/to/the/location");
URI absolute =URI.create("/this/is/an/absolute/path/to/the/location/of/my/file");
URI relative = base.relativize(absolute);

这将导致of/my/file


谢谢。我在想是否有一种方法可以更好地控制相对路径的内容。是否可能以类似优雅的方式获取“/the/location/of/my/file”的位置? - sc_ray
@sc_ray - 是的,请更改您的基本URI。 - jtahlborn
@sc_ray 看一下 FilegetParentFile 方法。File 包含用于转换为/从 URI 实例的方法。Java 7 用户 可能 可以使用 java.nio.file 包中的 Path 类型 - 我没有深入研究过它。 - McDowell

1

通过纯字符串操作,假设您知道基本路径并且只想要在基本路径下的相对路径,而且从不添加“../”系列:

String basePath = "/this/is/an/absolute/path/to/the/location/";
String absolutePath = "/this/is/an/absolute/path/to/the/location/of/my/file";
if (absolutePath.startsWith(basePath)) {
    relativePath = absolutePath.substring(basePath.length());
}

当然,使用了解路径逻辑的类(例如FileURI)肯定有更好的方法来完成这个任务。 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接