java – 从绝对路径中提取相对路径
发布时间:2020-12-15 04:57:12 所属栏目:Java 来源:网络整理
导读:这是一个看似简单的问题,但我无法以干净的方式进行.我有一个文件路径如下: /这/是/的/绝对/路径/到/的/位置/的/我的/文件 我需要的是从上面给出的路径中提取/ of / my / file,因为那是我的相对路径. 我想这样做的方式如下: String absolutePath = "/this/i
这是一个看似简单的问题,但我无法以干净的方式进行.我有一个文件路径如下:
/这/是/的/绝对/路径/到/的/位置/的/我的/文件 我需要的是从上面给出的路径中提取/ 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 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); 这将导致/ my / file. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |