Java Reference
In-Depth Information
Example 3−6: RemoveHTMLReader.java (continued)
catch(Exception e) {
System.err.println(e);
System.err.println("Usage: java RemoveHTMLReader$Test" +
" <filename>");
}
}
}
}
Filtering Lines of Text
Example 3-7 defines GrepReader , another custom input stream. This stream reads
lines of text from a specified Reader and returns only those lines that contain a
specified substring. In this way, it works like the Unix fgr ep command; it performs
a “grep” or search. GrepReader performs filtering, but it filters text a line at a time,
rather than a character at a time, so you extend BufferedReader instead of Fil-
terReader .
The code for this example is straightforward. The example includes an inner Test
class with a main() method that demonstrates the use of the GrepReader stream.
You might invoke this test program as follows:
% java com.davidflanagan.examples.io.GrepReader\$Test needle haystack.txt
Example 3−7: GrepReader.java
package com.davidflanagan.examples.io;
import java.io.*;
/**
* This class is a BufferedReader that filters out all lines that
* do not contain the specified pattern.
**/
public class GrepReader extends BufferedReader {
String pattern; // The string we are going to be matching.
/** Pass the stream to our superclass, and remember the pattern ourself */
public GrepReader(Reader in, String pattern) {
super(in);
this.pattern = pattern;
}
/**
* This is the filter: call our superclass's readLine() to get the
* actual lines, but only return lines that contain the pattern.
* When the superclass readLine() returns null (EOF), we return null.
**/
public final String readLine() throws IOException {
String line;
do { line = super.readLine(); }
while ((line != null) && line.indexOf(pattern) == -1);
return line;
}
/**
* This class demonstrates the use of the GrepReader class.
Search WWH ::




Custom Search