Close

How to resolve relative URI in Java?

[Updated: Apr 28, 2017, Created: Apr 28, 2017]

Java 

This code will resolve the relative base uri e.g. if current base uri is /path1/path2 then ../path3 will be resolved as /path1/path3.

public class RelativeUriExample {

  //e.g. currentUri => p/xyz/abc   targetUri => ../stu =>  p/xyz/stu
  public static String resolveRelativeUris(String currentUri, String targetUri) {
      if(targetUri.startsWith("/")){
          return targetUri;
      }

      String uri = targetUri;

      while (uri.startsWith("../")) {
          int i = currentUri.lastIndexOf("/");
          if(i==-1){
              break;
          }
          currentUri = currentUri.substring(0, i);
          uri = uri.substring(3);
      }

      return currentUri + "/" + uri;
  }

  public static void main(String[] args) {
      resolve("/a/b/c/d", "../../e");
      resolve("a/b/c/d", "../e");
      resolve("a/b/c/d", "e");
      resolve("a/b/c/d", "/e");
      resolve("/a/b/c/d", "/e");

  }
  private static void resolve(String current, String relative){
      String s = resolveRelativeUris(current, relative);
      System.out.printf("current:%s target:%s resolved:%s%n", current, relative, s);
  }
}

Output

current:/a/b/c/d target:../../e resolved:/a/b/e
current:a/b/c/d target:../e resolved:a/b/c/e
current:a/b/c/d target:e resolved:a/b/c/d/e
current:a/b/c/d target:/e resolved:/e
current:/a/b/c/d target:/e resolved:/e

Alternatively, we can use java.net.URL as shown in the following example

public class RelativeUriExample2 {

  public static void main(String[] args) throws MalformedURLException {
      resolve("/a/b/c/d", "../../e");
      resolve("a/b/c/d", "../e");
      resolve("a/b/c/d", "e");
      resolve("a/b/c/d", "/e");
      resolve("/a/b/c/d", "/e");
  }

  private static void resolve(String current, String relative) throws MalformedURLException {
      String s = "http://base" + (current.startsWith("/") ? "" : "/");
      URL base = new URL(s + current + (current.endsWith("/") ? "" : "/"));
      URL r = new URL(base, relative);
      String result = r.toString().substring(s.length());
      System.out.printf("current:%s target:%s resolved:%s%n", current, relative, result);
  }
}

Output

current:/a/b/c/d target:../../e resolved:/a/b/e
current:a/b/c/d target:../e resolved:a/b/c/e
current:a/b/c/d target:e resolved:a/b/c/d/e
current:a/b/c/d target:/e resolved:e
current:/a/b/c/d target:/e resolved:/e

See Also