Brian Brian - 1 year ago 153
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

in fancy ways, but it seems kind of hacky, especially in cases like:

An example would be:

String url1 = "";
String url2 = "";

System.out.println(relative(url1, url2)); // -> "../qux/quux/corge"

Answer Source

Java already offers this functionality, so the safest option would be to go the "standard" way:

String url1 = "";
String url2 = "";

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,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download