In Objective-C I use -[NSURL URLByDeletingLastPathComponent] to get parent URL. What\'s the equivalent of this in Java?
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 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
com.google.guava
guava
And, many more related functionalities are provided by this class InternetDomainName.