2012-04-15 13 views

Odpowiedz

20

Najkrótszy fragment kodu można myślę, jest to :

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

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

URI.resolve sprawdza się również w bardziej złożonych operacjach ... takich jak uri.resolve ("dir/file.txt"). – David

+0

Nie wydaje się, że działa to dla identyfikatorów URI z protokołem "jar: file: ...", który występuje z zasobami znajdującymi się w plikach JAR. –

3

Nie wiem o funkcji biblioteki, aby zrobić to w jednym kroku. Jednak następujące (wprawdzie uciążliwe) fragment kodu wierzę realizuje co jesteś po (i to może owinąć się w swoim własnym funkcji użyteczności):

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

W systemie Windows wprowadza to ukośniki tylne. – Sogartar

0

Tutaj jest bardzo proste rozwiązanie, które było najlepszym rozwiązaniem w moim przypadku użycia:

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

stworzyłem prostą funkcję, to był inspirowany przez kodeks File::getParent. W moim kodzie nie ma problemu z tylnymi ukośnikami w systemie Windows. Zakładam, że resourcePath jest częścią zasobów adresu URL, bez protokołu, domeny i numeru portu. (np. /articles/sport/atricle_nr_1234)

Powiązane problemy