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

sc_*_*ray 3 java relative-path code-cleanup filepath string-parsing

这是一个看似简单的问题,但我无法以干净的方式进行.我有一个文件路径如下:

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

我需要的是从上面给出的路径中提取/ 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();
Run Code Online (Sandbox Code Playgroud)

这可能会满足我的直接需求,但是有人可以建议一种更好的方法从java中提供的路径中提取子路径吗?

谢谢

McD*_*ell 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);
Run Code Online (Sandbox Code Playgroud)

这将导致of/my/file.