public URL(URL u, String s) throws MalformedURLException

This constructor builds an absolute URL from a relative URL; it is probably the constructor you'll use most frequently. For instance, you may be parsing an HTML document at http://www.macfaq.com/index.html and encounter a link to a file called vendor.html with no further qualifying information. In this case, you use the URL to the document that contains the link to provide the missing information. The constructor computes the new URL as http://www.macfaq.com/vendor.html. For example:

URL u1, u2;
  
try {
  URL u1 = new URL("http://www.macfaq.com/index.html");
  URL u2 = new URL (u1, "vendor.html");
}
catch (MalformedURLException e) {
   System.err.println(e);
}
The filename is removed from the path of u1, and the new filename vendor.html is appended to make u2. This constructor is particularly useful when you want to loop through a list of files that are all in the same directory. You can create a URL for the first file, and then use this initial URL to create URL objects for the other files by substituting their filenames. You also use this constructor when you want to create a URL relative to the applet's document or code base, which you retrieve using the getDocumentBase() or getCodeBase() methods of the Applet class. Example 5.4 is a very simple applet that uses getDocumentBase() to create a new URL object. You'll need to show the Java console to see the output.

The source

When using this constructor with getDocumentBase(), you frequently put the call to getDocumentBase() inside the constructor:

u2 = new URL(getDocumentBase(), "vendor.html");

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
This Chapter
Examples from other chapters
Home