2011-04-06 53 views

回答

30

你想是這樣的:

String path = new URL("http://www.costo.com/test1/test2").getPath(); 

其實這會給你/test1/test2。你只需要刪除第一/得到你想要的東西:

path = path.replaceFirst("/", ""); 

現在,您可以pathtest1/test2

+2

的人感覺這個嘗試後啞,請注意,這不是JavaScript代碼。這是java – 2017-08-01 20:15:11

4
URL url = new URL("http://www.google.com/in/on"); 
System.out.println(url.getPath()); 

另請參見

2

使用URL類的URL.getPath()方法。

1

你可以這樣做:

URL url = new URL("http://www.costo.com/test1/test2"); 
    System.out.println(url.getPath()); 
4

我不得不使用Java URL類從URL只是提取路徑性能的懷疑和認爲這是矯枉過正。

因此我寫了三種方法,它們都使用不同的方式從給定的URL中提取路徑。

  1. 第1種方法使用來自Java URL類的URL.getPath方法。
  2. 第二種方法使用正則表達式我在SO中找到了(我失去了源代碼鏈接,否則我會在這裏給作者點數)。
  3. 第三種方法使用數組拆分並加入獲得相同的結果。

對於給定的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; 
    } 
+0

切勿使用'System.currentTimeMillis()'進行微基準測試。使用nano,這更準確。請記住,這不是一個真正的基準測試,我強烈建議使用基準測試工具,http://openjdk.java.net/projects/code-tools/jmh/ – Panthro 2017-08-25 11:50:54