如何在Java中获取父URL?

在Objective-C中,我使用-[NSURL URLByDeletingLastPathComponent]来获取父URL。 在Java中,这相当于什么?

我能想到的最短代码片段是这样的:

 URI uri = new URI("http://www.stackoverflow.com/path/to/something"); URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".") 

我不知道库函数只需一步完成。 但是,我相信以下(当然是繁琐的)代码完成了你所追求的(并且你可以将它包装在你自己的实用程序函数中):

 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 ); } } 

这是一个非常简单的解决方案,这是我的用例中最好的方法:

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

我创建了简单的函数,我的灵感来自File::getParent的代码。 在我的代码中,Windows上的反斜杠没有问题。 我假设resourcePath是URL的资源部分,没有协议,域和端口号。 (例如/articles/sport/atricle_nr_1234