How to get parent URL in Java?
Asked Answered
N

7

16

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

Nitroparaffin answered 15/4, 2012 at 2:59 Comment(0)
S
32

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(".");
Seashore answered 15/4, 2012 at 3:35 Comment(2)
URI.resolve is also great for more complex operations... like uri.resolve("dir/file.txt")Mainis
This does not seem to work for URIs with the protocol "jar:file:...", which occurs with resources that are located in JAR files.Secretarygeneral
S
4

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( "https://mcmap.net/q/717339/-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 );
    }
}
Salpingitis answered 15/4, 2012 at 3:33 Comment(1)
On Windows this introduces back slashes.Pinkney
H
3

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 )

Harrisharrisburg answered 20/3, 2017 at 10:29 Comment(0)
K
1

The simple solution offered by Guava library.

Code:

URL url = new URL("https://www.ibm.watson.co.uk");
String host = url.getHost();

InternetDomainName parent = InternetDomainName.from(host).parent(); // returns ibm.watson.co.uk
System.out.println("Immediate ancestor: "+parent);


ImmutableList<String> parts = InternetDomainName.from(host).parts(); 
System.out.println("Individual components:  "+parts);


InternetDomainName name = InternetDomainName.from(host).topPrivateDomain(); // watson.co.uk
System.out.println("Top private domain - " + name);

Output:

Immediate ancestor: ibm.watson.co.uk

Individual components:  [www, ibm, watson, co, uk]

Top private domain - watson.co.uk

For reference: https://guava.dev/releases/snapshot/api/docs/com/google/common/net/InternetDomainName.html

Dependency required:

https://mvnrepository.com/artifact/com.google.guava/guava

I'm using version 19.0

<dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
</dependency>

And, many more related functionalities are provided by this class InternetDomainName.

Kamakura answered 29/5, 2020 at 6:11 Comment(0)
L
0

Using java.nio.file.Paths this can be done in a single line.

Eg:

String parent = Paths.get("https://mcmap.net/q/717339/-how-to-get-parent-url-in-java/").getParent().toString();
System.out.println(parent);

Will print:

https:/stackoverflow.com/questions/10159186

Keep in mind the https:/ is missing a slash so you can add that in with another replace:

String parent = Paths.get("https://mcmap.net/q/717339/-how-to-get-parent-url-in-java/").getParent().toString().replace("https:/","https://");

System.out.println(parent);

Will print:

https://stackoverflow.com/questions/10159186
Lorca answered 1/2, 2022 at 23:1 Comment(0)
R
0

Much more concise way

import java.nio.file.Paths;
URI child=....;
URI parent=Paths.get(child).getParent().toUri();

That's it..

Ricketts answered 15/4, 2022 at 1:43 Comment(0)
S
0

If you have a javax.ws.rs.core.UriBuilder :

URI location;
UriBuilder.fromUri(location).path("..").build().normalize();
Shamefaced answered 2/3, 2023 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.