获取Java中两个URI的相对路径

时间:2012-05-29 14:34:56

标签: java uri

我有两个URI:

http://www.google.de/blank.gif

http://www.google.de/sub/

我想要从http://www.google.de/sub/http://www.google.de/blank.gif so的相对路径,结果为../blank.gif

URI.relativize()在这里不起作用:/

谢谢!

2 个答案:

答案 0 :(得分:6)

Apache URIUtils应该可行。如果您不想引入外部库,这里是一个方法的简单实现,该方法应该正确解析java.net.URI无法处理的情况的相对URI(即基URI路径不是前缀的情况)子URI路径)。

public static URI relativize(URI base, URI child) {
  // Normalize paths to remove . and .. segments
  base = base.normalize();
  child = child.normalize();

  // Split paths into segments
  String[] bParts = base.getPath().split("\\/");
  String[] cParts = child.getPath().split("\\/");

  // Discard trailing segment of base path
  if (bParts.length > 0 && !base.getPath().endsWith("/")) {
    bParts = Arrays.copyOf(bParts, bParts.length - 1);
  }

  // Remove common prefix segments
  int i = 0;
  while (i < bParts.length && i < cParts.length && bParts[i].equals(cParts[i])) {
    i++;
  }

  // Construct the relative path
  StringBuilder sb = new StringBuilder();
  for (int j = 0; j < (bParts.length - i); j++) {
    sb.append("../");
  }
  for (int j = i; j < cParts.length; j++) {
    if (j != i) {
      sb.append("/");
    }
    sb.append(cParts[j]);
  }

  return URI.create(sb.toString());
}

请注意,这并不强制基础和子级具有相同的方案和权限 - 如果您希望它处理一般情况,则必须添加它。这可能不适用于所有边界情况,但它对你不利。

答案 1 :(得分:3)

我认为您可以使用Apache URIUtils

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URIUtils.html#resolve%28java.net.URI,%20java.net.URI%29

决心

公共静态URI解析(URI baseURI,                           URI引用)

Resolves a URI reference against a base URI. Work-around for bugs in java.net.URI (e.g. )

Parameters:
    baseURI - the base URI
    reference - the URI reference 
Returns:
    the resulting URI

示例:

http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/test/java/org/apache/http/client/utils/TestURIUtils.java