}
}
if(chars != 0) {
++lines;
}
}
public static void main(String args[]) {
FileReader fr;
try {
if (args.length == 0) { // We're working with stdin
wc(new InputStreamReader(System.in));
}
else { // We're working with a list of files
for (int i = 0; i < args.length; i++) {
fr = new FileReader(args[i]);
wc(fr);
}
}
}
catch (IOException e) {
return;
}
System.out.println(lines + " " + words + " " + chars);
}
}
The wc( ) method operates on any input stream and counts the number of characters,
lines, and words. It tracks the parity of words and whitespace in the lastNotWhite variable.
When executed with no arguments, WordCount creates an InputStreamReader object
using System.in as the source for the stream. This stream is then passed to wc( ), which does
the actual counting. When executed with one or more arguments, WordCount assumes that
these are filenames and creates FileReaders for each of them, passing the resultant FileReader
objects to the wc( ) method. In either case, it prints the results before exiting.
Improving wc( ) Using a StreamTokenizer
An even better way to look for patterns in an input stream is to use another of Java's I/O
classes: StreamTokenizer. Similar to StringTokenizer from Chapter 18, StreamTokenizer
breaks up the input stream into tokens that are delimited by sets of characters. It has this
constructor:
StreamTokenizer(Reader inStream)
Here, inStream must be some form of Reader.
StreamTokenizer defines several methods. In this example, we will use only a few. To
reset the default set of delimiters, we will employ the resetSyntax( ) method. The default set
of delimiters is finely tuned for tokenizing Java programs and is thus too specialized for this
example. We declare that our tokens, or "words," are any consecutive string of visible characters
delimited on both sides by whitespace.
We use the eolIsSignificant( ) method to ensure that newline characters will be delivered
as tokens, so we can count the number of lines as well as words. It has this general form:
void eolIsSignificant(boolean eolFlag)
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home