Java Reference
In-Depth Information
The output is:
http: //www.ncsa.uiuc.edu/HTMLPrimer.html#GS is the same file as
http: //www.ncsa.uiuc.edu/HTMLPrimer.html#HD
Conversion
URL has three methods that convert an instance to another form: toString() ,
toExternalForm() , and toURI() .
Like all good classes, java.net.URL has a toString() method. The String produced
by toString() is always an absolute URL, such as http://www.cafeaulait.org/javatuto‐
rial.html . It's uncommon to call toString() explicitly. Print statements call to
String() implicitly. Outside of print statements, it's more proper to use toExternal
Form() instead:
public String toExternalForm ()
The toExternalForm() method converts a URL object to a string that can be used in an
HTML link or a web browser's Open URL dialog.
The toExternalForm() method returns a human-readable String representing the
URL. It is identical to the toString() method. In fact, all the toString() method does
is return toExternalForm() .
Finally, the toURI() method converts a URL object to an equivalent URI object:
public URI toURI () throws URISyntaxException
We'll take up the URI class shortly. In the meantime, the main thing you need to know
is that the URI class provides much more accurate, specification-conformant behavior
than the URL class. For operations like absolutization and encoding, you should prefer
the URI class where you have the option. You should also prefer the URI class if you need
to store URLs in a hashtable or other data structure, since its equals() method is not
blocking. The URL class should be used primarily when you want to download content
from a server.
The URI Class
A URI is a generalization of a URL that includes not only Uniform Resource Locators
but also Uniform Resource Names (URNs). Most URIs used in practice are URLs, but
most specifications and standards such as XML are defined in terms of URIs. In Java,
URIs are represented by the java.net.URI class. This class differs from the
java.net.URL class in three important ways:
Search WWH ::




Custom Search