2012-04-15 8 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

+0

これは、 "jar:file:..."というプロトコルのURIでは機能しないようです。 JARファイルにあるリソースで発生します。 –

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

これは、バックスラッシュを導入しています。 – Sogartar

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

関連する問題