Package java.net contains class URL , which is used for dealing with URLs in
Java. An instance of class URL contains a description of one URL. It has methods
for getting components of the url and for reading the file named by the URL.
Usually, one uses one of two constructors when creating a new URL . First,
creates an instance for String s, which must be a URL according to the rules
given above. Second, suppose URL c describes a directory and we want to create
a URL for a file s that is within the directory, Use the following new-expression
to create it:
For example, we might use the following:
URL dir= new URL("http://www.cs.cornell.edu");
URL file= new URL(dir, "gries/programlive/plive.html");
Both constructors throw a MalformedURLException if there is a problem.
Also, note that new URL(s) is equivalent to new URL( null , s) .
The specification of the second constructor is quite detailed, indicating what
happens when both c and s contain protocols and when s begins with "/" . Please
look at the specification in the API package for details.
Getter and toString methods
Class URL contains a number of methods for accessing the different parts of
the URL that it describes. Here are some:
getFile() the file name, as a String
getHost() the host, or domain name, as a String
getPath() the path, as a String
getPort() the port number, as an int (-1 if port not set)
getProtocol() the protocol, as a String
As you might expect, class URL has a toString method, which produces a
String representation of the URL that it describes.
Reading the file given by a URL
A search engine like google seems to find appropriate files for a query almost
instantaneously. The search engine is able to perform so quickly because infor-
mation about web pages is already stored on its computers. Many computers in