Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find relative path from one URL to another in Java [duplicate]

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"
like image 245
Brian Avatar asked Mar 11 '23 13:03

Brian


2 Answers

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 thegetPath()` method, should yield the correct relative path.

like image 180
PNS Avatar answered Apr 06 '23 17:04

PNS


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, "");
}
like image 30
Titus Avatar answered Apr 06 '23 19:04

Titus