问题
This is a seemingly simple problem but I am having trouble doing it in a clean manner. I have a file path as follows:
/this/is/an/absolute/path/to/the/location/of/my/file
What I need is to extract /of/my/file from the above given path since that is my relative path.
The way I am thinking of doing it is as follows:
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();
This will probably serve my immediate needs but can somebody suggest a better way of extracting sub-paths from a provided path in java?
Thanks
回答1:
Use the 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);
This will result in of/my/file
.
回答2:
With pure string operations and assuming you know the base path and assuming you only want relative paths below the base path and never prepend a "../" series:
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());
}
There are surely better ways to do this with classes that are aware of path logic, such as File
or URI
, though. :)
来源:https://stackoverflow.com/questions/9826769/extracting-relative-paths-from-absolute-paths