如何获得父URL在Java中?(How to get parent URL in Java?)

2019-06-23 15:21发布

在Objective-C我用-[NSURL URLByDeletingLastPathComponent]让家长URL。 什么是这个在Java中的等价物?

Answer 1:

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

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

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


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


Answer 3:

这是非常简单的解决方案,它是在我使用的情况下,最好的办法:

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



文章来源: How to get parent URL in Java?
标签: java url