590 Part II: The Java Library
}
}
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);
}
}
Thewc( )method operates on any input stream and counts the number of characters,
lines, and words. It tracks the parity of words and whitespace in thelastNotWhitevariable.
When executed with no arguments,WordCountcreates anInputStreamReaderobject
usingSystem.inas the source for the stream. This stream is then passed towc( ), which does
the actual counting. When executed with one or more arguments,WordCountassumesthat
these are filenames and createsFileReaders for each of them, passing the resultantFileReader
objects to thewc( )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 toStringTokenizerfrom Chapter 18,StreamTokenizer
breaks up the input stream intotokensthat are delimited by sets of characters. It has this
constructor:
StreamTokenizer(ReaderinStream)
Here,inStreammust be some form ofReader.
StreamTokenizerdefines several methods. In this example, we will use only a few. To
reset the default set of delimiters, we will employ theresetSyntax( )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 theeolIsSignificant( )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(booleaneolFlag)