How to get parent URL in Java?

2019-01-20 08:03发布

In Objective-C I use -[NSURL URLByDeletingLastPathComponent] to get parent URL. What's the equivalent of this in Java?

标签: java url
3条回答
地球回转人心会变
2楼-- · 2019-01-20 08:42

Here is very simple solution which was the best approach in my use case:

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

I created simple function, I was inspired by the code of File::getParent. In my code there is no issue with back slashes on Windows. I assume that resourcePath is resource part of URL, without protocol, domain and port number. (e.g. /articles/sport/atricle_nr_1234 )

查看更多
爷的心禁止访问
3楼-- · 2019-01-20 08:54

Shortest snippet of code I can think of is this:

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

URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".")
查看更多
Melony?
4楼-- · 2019-01-20 08:55

I don't know of library function to do this in one step. However, the following (admittedly cumbersome) bit of code I believe accomplishes what you're after (and you could wrap this up in your own utility function):

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 );
    }
}
查看更多
登录 后发表回答