Using the StreamTokenizer class

This java code example shows how you can use the StreamTokenizer class to count words and numbers in a file.
In the example we open a stream to a file with help of the FileReader class.
We construct the StreamTokenizer object with this stream as argument and start looping through it.

The ‘nextToken’ method returns an int which indicates of what type the token is and we can match the int value to one of the static variables of the StreamTokenizer class to determine of what type the current token is.
The iterations continues until the end of file token is reached. For each token we check the tokenizers variable ‘ttype’, which holds the current token type, against the static variables to see if it is a number or a word and increment count variables accordingly.
So if the file content would look like this:

The output would be:

Search for more Java info on this site here:
Custom Search

Please type any questions here.