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 中提供的路径中提取子路径吗?

谢谢

4

2 回答 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.

于 2012-03-22T16:53:32.250 回答
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());
}

但是,对于知道路径逻辑的类,肯定有更好的方法来做到这一点,例如Fileor URI。:)

于 2012-03-22T16:59:35.060 回答