这是一个看似简单的问题,但我很难以干净的方式完成它。我有一个文件路径如下:
/这个/是/一个/绝对/路径/到/我的/文件的/位置
我需要的是从上面给定的路径中提取 /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中提供的路径中提取子路径吗?
Thanks
Use the URI类 http://docs.oracle.com/javase/7/docs/api/java/net/URI.html:
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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)