Brian Brian - 4 months ago 33
Java Question

Find relative path from one URL to another in Java

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"

PNS PNS
Answer

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