Java Reference
In-Depth Information
Example 3−7: GrepReader.java (continued)
* It prints the lines of a file that contain a specified substring.
**/
public static class Test {
public static void main(String args[]) {
try {
if (args.length != 2)
throw new IllegalArgumentException("Wrong number of args");
GrepReader in=new GrepReader(new FileReader(args[1]), args[0]);
String line;
while((line = in.readLine()) != null) System.out.println(line);
in.close();
}
catch (Exception e) {
System.err.println(e);
System.out.println("Usage: java GrepReader$Test" +
" <pattern> <file>");
}
}
}
}
A Custom HTML Output Stream
One of the first common uses of Java was to run applets—miniature programs
delivered over the Internet—within web browsers. (We'll discuss applets in more
detail in Chapter 15, Applets .) Because applets run within web browsers, and
browsers are powerful tools for displaying HTML documents, it seems logical that
there should be some way to use the HTML display capabilities of the browser
from within an applet.
Example 3-8 shows a custom output stream named HTMLWriter that provides
exactly this capability. When a new HTMLWriter stream is created, it communicates
with the web browser using JavaScript commands and tells the browser to open a
new window. Then, when HTML-formatted text is written to this stream, it passes
that text, through JavaScript, to the new web-browser window, which parses and
displays it. This class relies on Navigator's LiveConnect technology and the
netscape.javascript.JSObject class. It is designed for use with Netscape Naviga-
tor 4.0 or later, although Microsoft has implemented a version of this technology,
and this example should also work with recent versions of Internet Explorer.
Note the implementation of the write() and close() methods, and the no-op
implementation of the flush() method. These are the three abstract methods of
Writer that must be implemented by every concrete subclass. Note also the
closeWindow() method that this class adds.
You are not expected to understand the JSObject class or the JavaScript com-
mands sent to the browser through it. If you are interested in learning about these
things, I recommend my JavaScript topic, JavaScript: The Definitive Guide , also
published by O'Reilly.
The example includes an inner applet class named Test that demonstrates how to
use the HTMLWriter class. This applet reads a URL specified in an applet parameter
Search WWH ::




Custom Search