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

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

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

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

谢谢

使用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

使用纯字符串操作并假设您知道基本路径并假设您只希望在基本路径下面的相对路径并且从不预先添加“../”系列:

 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 ,肯定有更好的方法可以做到这一点。 🙂