Extracting relative paths from absolute paths

This is a seemingly simple problem, but I am having problems with its clean way. I have a file path like this:

/ this / is / an / absolute / path / to // position // mine / file

I need to extract / from / my / file from the above path as this is my relative path.

The way I am going to do 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 anyone suggest a better way to extract sub items from a provided path in java?



source to share

2 answers

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




With pure string operations and assuming you know the base path and assume you only want relative paths below the base path and never add the "../" 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());


Of course, there are more efficient ways to do this with classes that know the logic of the path, like File

or URI

. :)



All Articles