Java Reference
In-Depth Information
Port = 80
File name = /data/x.html
Target = d
Yo u can construct a URL object from a URL string:
URL kth = new URL ("http://www.kth.se/index.html");
or from individual string components as in:
URL kth = new URL ( " http " , " www.kth.se " , " /index.html " );
When you attempt to create an instance of URL , the constructor checks the compo-
nents for proper form and value. If the URL specification is invalid, the constructor
throws a MalformedURLException ,which is a checked exception and must
be caught.
Typically one of the first tasks that new Java programmers want to do for their
ownwork is to read a file from an applet. This might involve a simple data file
in text format such as a list or a table of values and labels. We have learned to
read image files and audio files from applets and applications but have not yet
read a text file. This is in fact fairly easy to do. However, keep in mind that for
applets the SecurityManager in the browser's JVM restricts access to only
those files on the host system of the applet. (We discuss security managers further
in Chapter 14.)
Below we show the applet ReadFileViaURL ,which reads a text file located
with an instance of the URL class. It uses a method from the URL class that
provides file access via an instance of InputStream (see Chapter 9). We wrap
this stream with an InputStreamReader to provide proper character handling.
We in turn wrap this class with BufferedReader ,which provides buffering
to smooth out the stream flow and also contains the convenient readLine()
method that grabs an entire line and returns it as a string.
The program can also run as a standalone application. We see in the
readFile() method how to obtain a URL object from a File object for local
files. Figure 13.3 shows the interface in application mode after reading the default
file.
Figure 13.3 The
ReadFileViaURL applet
displays the text file that it
read via a URL address.
Search WWH ::




Custom Search