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

时间:2012-03-22 16:46:11

标签: java relative-path filepath string-parsing code-cleanup

这是一个看似简单的问题,但我在以干净的方式做这件事时遇到了麻烦。我有一个文件路径如下:

/这个/是/一个/绝对/路径/到/与/位置/的/我/文件

我需要从上面给出的路径中提取/ / 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中提供的路径中提取子路径吗?

由于

2 个答案:

答案 0 :(得分:11)

使用URI class

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

答案 1 :(得分: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。 :)

相关问题