Objective-C では-[NSURL URLByDeletingLastPathComponent]
、親 URL を取得するために使用します。Javaでこれに相当するものは何ですか?
17378 次
5 に答える
31
私が考えることができるコードの最短スニペットはこれです:
URI uri = new URI("http://www.stackoverflow.com/path/to/something");
URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".");
于 2012-04-15T03:35:28.530 に答える
4
これをワンステップで行うライブラリ関数がわかりません。ただし、次の(確かに面倒な)コードのビットは、目的を達成すると信じています(これを独自のユーティリティ関数にまとめることができます):
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 );
}
}
于 2012-04-15T03:33:37.520 に答える