Java Reference
In-Depth Information
Example 3−5: Compress.java (continued)
}
if ((new File(to)).exists()) { // Make sure not to overwrite
System.err.println("Compress: won't overwrite existing file: "+
to);
System.exit(0);
}
// Finally, call one of the methods defined above to do the work.
if (directory) Compress.zipDirectory(from, to);
else Compress.gzipFile(from, to);
}
}
}
Filtering Character Streams
FilterReader is an abstract class that defines a null filter; it reads characters from
a specified Reader and returns them with no modification. In other words, Filter-
Reader defines no-op implementations of all the Reader methods. A subclass must
override at least the two read() methods to perform whatever sort of filtering is
necessary. Some subclasses may override other methods as well. Example 3-6
shows RemoveHTMLReader , which is a custom subclass of FilterReader that reads
HTML text from a stream and filters out all of the HTML tags from the text it
returns.
In the example, you implement the HTML tag filtration in the three-argument ver-
sion of read() , and then implement the no-argument version in terms of that more
complicated version. The example includes an inner Test class with a main()
method that shows how you might use the RemoveHTMLReader class.
Note that you can also define a RemoveHTMLWriter class by performing the same
filtration in a FilterWriter subclass. Or, to filter a byte stream instead of a charac-
ter stream, you can subclass FilterInputStream and FilterOutputStream .
RemoveHTMLReader is only one example of a filter stream. Other possibilities
include streams that count the number of characters or bytes processed, convert
characters to uppercase, extract URLs, perform search-and-replace operations, con-
vert Unix-style LF line terminators to Windows-style CRLF line terminators, and so
on.
Example 3−6: RemoveHTMLReader.java
package com.davidflanagan.examples.io;
import java.io.*;
/**
* A simple FilterReader that strips HTML tags (or anything between
* pairs of angle brackets) out of a stream of characters.
**/
public class RemoveHTMLReader extends FilterReader {
/** A trivial constructor. Just initialize our superclass */
public RemoveHTMLReader(Reader in) { super(in); }
Search WWH ::




Custom Search