Given two paths, how can I compute the relative path from one to another?
I thought about using split
in fancy ways, but it seems kind of hacky, especially in cases like: "http://foo.com/bar/baz#header"
or "http://foo.com/bar/baz"?param=value
.
An example would be:
String url1 = "http://foo.com/bar/baz";
String url2 = "http://foo.com/bar/qux/quux/corge";
System.out.println(relative(url1, url2)); // -> "../qux/quux/corge"
Java
already offers this functionality, so the safest option would be to go the "standard" way:
String url1 = "http://foo.com/bar/baz";
String url2 = "http://foo.com/bar/qux/quux/corge";
Path p1 = Paths.get(url1);
Path p2 = Paths.get(url2);
Path p = p1.relativize(p2);
System.out.println("Relative path: " + p);
The print
statement above shows the correct relative path - i.e., in this case,
../qux/quux/corge
If the protocol (e.g., http vs https) and host parts can be different, then converting url1
and url2
above, into URL
objectsand using the
getPath()` method, should yield the correct relative path.
You can do something like this:
public static String relative(String url1, String url2){
String[] parts = url1.split("/");
String similar = "";
for(String part:parts){
if(url2.contains(similar+part+"/")){
similar+=part+"/";
}
}
return "./"+url2.replace(similar, "");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With