Java: what is the easiest way to get the whole URL except for the last part?

consider url

  http://www.google.com/a/b/myendpoint

All I want is the following

  http://www.google.com/a/b/

One approach is to split the string URL and combine all the components except the last.

I think there could be a better way?

+4
source share
3 answers

You can use lastIndexOf() :

 url.substring(0, url.lastIndexOf('/') + 1) 

 String url = "http://www.google.com/a/b/myendpoint"; System.out.println(url.substring(0, url.lastIndexOf('/') + 1)); 
  http://www.google.com/a/b/
+9
source

Use one of the following two options:

 pathofURL = url.subString(0, url.lastIndexOf('/') + 1); 

or if he has no request

 pathofURL = url.getProtocol() + "://" + url.getAuthority() + url.getPath(); pathofURL = pathofURL.subString(0, pathofURL.lastIndexOf('/') + 1); 

It has only a request.

 pathofURL = url.getProtocol() + "://" + url.getAuthority() + url.getPath(); 

It has a request and a link

 pathofURL = url.getProtocol() + "://" + url.getAuthority() + url.getFile(); 

Hope this helps, check the url and use any of the above.

+1
source

The simplest one uses the URI.resolve method: url.toURI().resolve("").toURL() . (You can start right away with a URI.)

 URL url = new URL("http://www.google/intl/eo/index.html"); URL url2 = url.toURI().resolve("favicon.ico").toURL(); // Or "" for the question. System.out.println("url2: " + url2.toExternalForm()); // url2: http://www.google/intl/eo/favicon.ico 
0
source

All Articles