2012-04-15 38 views

回答

20

最短的代碼,我能想到的片段是這樣的:

URI uri = new URI("http://www.stackoverflow.com/path/to/something"); 

URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".") 
+1

對於更復雜的操作,URI.resolve也很棒......就像uri.resolve(「dir/file.txt」) – David 2013-10-20 19:25:51

+0

這對於協議爲「jar:file:...」的URI似乎不起作用,它與位於JAR文件中的資源一起發生。 – 2016-10-01 19:52:48

3

我不知道庫函數在一個步驟中做到這一點。然而,代碼我相信下面的(當然繁瑣)位完成後,你在做什麼(你可以在自己的效用函數包裝這件事):

import java.io.File; 
import java.net.MalformedURLException; 
import java.net.URL; 

public class URLTest 
{ 
    public static void main(String[] args) throws MalformedURLException 
    { 
     // make a test url 
     URL url = new URL("http://stackoverflow.com/questions/10159186/how-to-get-parent-url-in-java"); 

     // represent the path portion of the URL as a file 
     File file = new File(url.getPath()); 

     // get the parent of the file 
     String parentPath = file.getParent(); 

     // construct a new url with the parent path 
     URL parentUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), parentPath); 

     System.out.println("Child: " + url); 
     System.out.println("Parent: " + parentUrl); 
    } 
} 
+2

在Windows上,這引入了反斜槓。 – Sogartar 2013-01-18 12:56:39

0

這是非常簡單的解決方案,它是在我使用的情況下,最好的辦法:

private String getParent(String resourcePath) { 
    int index = resourcePath.lastIndexOf('/'); 
    if (index > 0) { 
     return resourcePath.substring(0, index); 
    } 
    return "/"; 
} 

我創建了簡單的功能,我被代碼啓發3210。在我的代碼中,Windows上的反斜槓沒有問題。我認爲resourcePath是URL的資源部分,沒有協議,域和端口號。 (例如/articles/sport/atricle_nr_1234