Java Reference
In-Depth Information
Before you can load anything, you must create a new instance of the class
URL
that repre-
sents the address of the resource you want to load. URL is an acronym for
uniform
resource locator
, and it refers to the unique address of any document or other resource
accessible on the Internet.
URL
is part of the
java.net
package, so you must import the package or refer to the class
by its full name in your programs.
To create a new
URL
object, use one of four constructors:
URL(
String
)
—Creates a
URL
object from a full web address such as
http://www.java21days.com
or ftp://ftp.netscape.com.
n
URL(
URL
,
String
)
—Creates a
URL
object with a base address provided by the
specified
URL
and a relative path provided by the
String
.
n
URL(
String
,
String
,
int
,
String
)
—Creates a new
URL
object from a protocol
(such as “http” or “ftp”), hostname (such as
“www.cnn.com”
or “web.archive.org”),
port number (80 for HTTP), and a filename or pathname.
n
17
URL(
String
,
String
,
String
)
—The same as the previous constructor minus the
port number.
n
When you use the
URL(
String
)
constructor, you must deal with
MalformedURLException
objects, which are thrown if the
String
does not appear to be a valid URL. These objects
can be handled in a
try
-
catch
block:
try {
URL load = new URL(“http://www.samspublishing.com”);
} catch (MalformedURLException e) {
System.out.println(“Bad URL”);
}
The
WebReader
application in Listing 17.1 uses the four-step technique to open a connec-
tion to a website and read a text document from it. When the document is fully loaded, it
is displayed in a text area.
LISTING 17.1
The Full Text of
WebReader.java
1: import javax.swing.*;
2: import java.awt.*;
3: import java.awt.event.*;
4: import java.net.*;
5: import java.io.*;
6:
7: public class WebReader extends JFrame {
8: JTextArea box = new JTextArea(“Getting data ...”);
9: