35

I have a URL:

URL url=new URL("https://example.com/aa/bb/cc/file.html");

and a relative path:

String relativePath="../file2.html"; //maybe is "/file3.html"

I want to get http://example.com/aa/bb/file2.html using variable url and relativePath

How to do it?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Koerr
  • 15,215
  • 28
  • 78
  • 108

6 Answers6

65
new URL(url, relativePath);
Arne Deutsch
  • 14,629
  • 5
  • 53
  • 72
  • 1
    +1. More details on the Java API: http://download.oracle.com/javase/6/docs/api/java/net/URL.html – Benoit Courtine Sep 08 '10 at 07:46
  • No, the method exist since 1.0. Here's at least the doc for 1.3 (could not find 1.0 ;). http://download.oracle.com/javase/1.3/docs/api/java/net/URL.html#URL%28java.net.URL,%20java.lang.String%29 – Arne Deutsch Sep 08 '10 at 08:01
  • 3
    This resolves the relative URIs as per RFC2396, not as per RFC1808 as browsers seem to do. e.g. relative URI "?page=33" with base "http://site/path/list" will resolve differently. – jsalvata Dec 30 '11 at 11:42
10

Try operating winth the class URI instead of the URL.

To get the URI from your URL:

java.net.URI anURI=url.toUri();

Then, to resolve the relative URI:

URI resultURI=anURI.resolve(relativePath);

And at last, to get an URL type use de method toUrl() of the URI result variable, and you've got it.

Tomas Narros
  • 13,390
  • 2
  • 40
  • 56
10

If you want to build an URL pointing to a relative file, you can use:

URL url = new URL(new URL("file:"), "./myLocalFile.txt");
Camilo Díaz Repka
  • 4,805
  • 5
  • 43
  • 68
3

When building relative URL, keep in mind that the base is path to current package, not file. I mean: the referer file is in .../myProject/src/pckg/javafile.java and the referated file is in .../myProject/some-other/nice.file, then the relative reference should look like this:

URL url = new URL(new URL("file:"), "./../some-other/nice.file");

and this works for me as well:

URL url = new URL("file:./../some-other/nice.file");
Jarda
  • 566
  • 1
  • 9
  • 33
  • I'm not sure if people noticed that the second form is the most interesting one. No need to split protocol and the rest – Jako Jul 03 '20 at 14:01
0

What I found worked is this:

new URL("file:./src/gui/Something.fxml")
Julius
  • 1
-1

This worked for my code
URL url=Myclass.class.getResource("/com/fnf/si/DepAcctInq_V02.wsdl");

June7
  • 19,874
  • 8
  • 24
  • 34
Bhabani
  • 1
  • 2