How to get parent url in java?

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

+7
source share
3 answers

The shortest code snippet I can come up with:

 URI uri = new URI("http://www.stackoverflow.com/path/to/something"); URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve(".") 
+20
source

I do not know the library functions to do this in one step. However, the next (admittedly cumbersome) bit of code that I believe is doing what you need (and you can wrap this 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 ); } } 
+3
source

Here is a very simple solution that was the best in my case:

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

I created a simple function, I was inspired by the File::getParent code. My code has no backslash issues on Windows. I assume that resourcePath is the resource part of the URL, without protocol, domain and port number. (e.g. /articles/sport/atricle_nr_1234 )

0
source

All Articles