如何在Java中获取父URL?

2022-09-03 09:21:58

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


答案 1

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

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

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

答案 2

我不知道库函数可以在一步中完成此操作。但是,我相信以下(诚然很麻烦)代码部分可以完成您所追求的目标(您可以在自己的实用程序函数中将其打包):

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