【发布时间】:2011-07-30 17:11:38
【问题描述】:
【问题讨论】:
【问题讨论】:
你想要这样的东西:
String path = new URL("http://www.costo.com/test1/test2").getPath();
实际上这会给你/test1/test2。您只需删除第一个 / 即可获得所需内容:
path = path.replaceFirst("/", "");
现在您将在path 中拥有test1/test2。
【讨论】:
我对使用 Java URL 类仅从 URL 中提取路径有性能疑问,并认为这是一种矫枉过正。
因此我编写了三个方法,它们都使用不同的方式从给定的 URL 中提取路径。
对于给定的 URL,所有三个方法都被调用了 1000000 次。
结果是:
#1 (getPathviaURL) took: 860ms
#2 (getPathViaRegex) took: 3763ms
#3 (getPathViaSplit) took: 1365ms
代码 - 随意优化它:
public static void main(String[] args) {
String host = "http://stackoverflow.com/questions/5564998/how-to-get-the-path-of-a-url";
long start1 = System.currentTimeMillis();
int i = 0;
while (i < 1000000) {
getPathviaURL(host);
i++;
}
long end1 = System.currentTimeMillis();
System.out.println("#1 (getPathviaURL) took: " + (end1 - start1) + "ms");
Pattern p = Pattern.compile("(?:([^:\\/?#]+):)?(?:\\/\\/([^\\/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?");
long start2 = System.currentTimeMillis();
int i2 = 0;
while (i2 < 1000000) {
getPathViaRegex(host, p);
i2++;
}
long end2 = System.currentTimeMillis();
System.out.println("#2 (getPathViaRegex) Took: " + (end2 - start2) + "ms");
long start3 = System.currentTimeMillis();
int i3 = 0;
while (i3 < 1000000) {
getPathViaSplit(host);
i3++;
}
long end3 = System.currentTimeMillis();
System.out.println("#3 (getPathViaSplit) took: " + (end3 - start3) + "ms");
}
public static String getPathviaURL(String url) {
String path = null;
try {
path = new URL(url).getPath();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
}
public static String getPathViaRegex(String url, Pattern p) {
Matcher m = p.matcher(url);
if (m.find()) {
return m.group(3);
}
return null;
}
public static String getPathViaSplit(String url) {
String[] parts = url.split("/");
parts = Arrays.copyOfRange(parts, 3, parts.length);
String joined = "/" + StringUtils.join(parts, "/");
return joined;
}
【讨论】:
System.currentTimeMillis() 进行微基准测试。使用 nano,更准确。请记住,这不是一个真正的基准测试,我强烈建议使用基准测试工具,openjdk.java.net/projects/code-tools/jmh
【讨论】:
使用URL类的URL.getPath()方法。
【讨论】:
你可以这样做:
URL url = new URL("http://www.costo.com/test1/test2");
System.out.println(url.getPath());
【讨论】:
如果您想从应用程序的 URL 中获取它,例如 http://localhost:8080/test1/test2/main.jsp。 使用可以使用
request.getRequestURI() //result will be like test1/test2
【讨论】:
我建议使用URI 类,因为它也可以处理相对路径。这是一个使用 URI 和 URL 实现相同的示例代码:
String urlStr = "http://localhost:8080/collections-in-java?error=true";
try {
URI uri = URI.create(urlStr);
System.out.println(uri.getPath());
URL url1 = new URL(urlStr);
System.out.println(url1.getPath());
} catch (MalformedURLException e) {
e.printStackTrace();
}
上面的代码会产生同样的结果。如果路径可能是相对的,则 URI 很有用,例如/some/path/collections-in-java?error=true
对于这种情况,URI.getPath() 将返回 /some/path/collections-in-java 但URL.getPath() 将抛出 MalformedURLException。
【讨论】: