Java – extract relative paths from absolute paths
•
Java
This is a seemingly simple question, but I can't do it in a clean way I have a file path as follows:
/This / is / absolute / path / to / location / my / file
What I need is to extract / of / my / file from the path given above, because that is my relative path
I want to do this 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 may meet my immediate needs, but can anyone suggest a better way to extract sub paths from the paths provided in Java?
thank you
Solution
Use 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 / my / file
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码