Java Reference
In-Depth Information
throw
new
RuntimeException
(
"shouldn't happen; all VMs recognize http"
);
}
This creates a
URL
object that points to
http://www.eff.org/blueribbon.html#intro
, using
the default port for the HTTP protocol (port 80). The file specification includes a ref‐
erence to a named anchor. The code catches the exception that would be thrown if the
virtual machine did not support the HTTP protocol. However, this shouldn't happen
in practice.
For the rare occasions when the default port isn't correct, the next constructor lets you
specify the port explicitly as an
int
. The other arguments are the same. For example,
this code fragment creates a
URL
object that points to
http://fourier.dur.ac.uk:8000/
~dma3mjh/jsci/
, specifying port 8000 explicitly:
try
{
URL
u
=
new
URL
(
"http"
,
"fourier.dur.ac.uk"
,
8000
,
"/~dma3mjh/jsci/"
);
}
catch
(
MalformedURLException
ex
)
{
throw
new
RuntimeException
(
"shouldn't happen; all VMs recognize http"
);
}
Constructing relative URLs
This constructor builds an absolute
URL
from a relative
URL
and a base
URL
:
public
URL
(
URL
base
,
String
relative
)
throws
MalformedURLException
For instance, you may be parsing an HTML document at
http://www.ibiblio.org/javafaq/
index.html
and encounter a link to a file called
mailinglists.html
with no further quali‐
fying 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.ibiblio.org/javafaq/mailinglists.html
. For example:
try
{
URL
u1
=
new
URL
(
"http://www.ibiblio.org/javafaq/index.html"
);
URL
u2
=
new
URL
(
u1
,
"mailinglists.html"
);
}
catch
(
MalformedURLException
ex
)
{
System
.
err
.
println
(
ex
);
}
The filename is removed from the path of
u1
and the new filename
mailinglists.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.
Other sources of URL objects
Besides the constructors discussed here, a number of other methods in the Java class
library return
URL
objects. In applets,
getDocumentBase()
returns the
URL
of the page
that contains the applet and
getCodeBase()
returns the
URL
of the applet
.class
file.