Get relative path of two URIs in Java
本问题已经有最佳答案,请猛点这里访问。
我有两个URI:
我想要从
谢谢!
ApacheUriutils应该可以工作。如果您不想拉入外部库,下面是一个方法的简单实现,该方法应该正确地解决
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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()); } |
请注意,这并不能强制基础和子级具有相同的方案和权限——如果您希望它处理一般情况,就必须添加这一点。这可能不适用于所有边界情况,但它适用于您的示例。
我想你可以用阿帕奇乌里乌斯
http://hc.apache.org/httpcomponents-client-ga/http client/apidocs/org/apache/http/client/utils/uri utils.html解析%28java.net.uri,%20java.net.uri%29
决定
公共静态URI解析(uri baseuri,参考URI)
1 2 3 4 5 6 7 | 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/http client/trunk/http client/src/test/java/org/apache/http/client/utils/testuriutils.java