File
Count words and numbers in a file
This is an example of how to count the words and numbers in a File. Counting the words and numbers in a File implies that you should:
- Create a new FileReader.
- Create a new StreamTokenizer that parses the given FileReader.
- Keep an int word counter and a number word counter.
- Iterate over the tokens of the tokenizer.
- For every token, check the type of the token, using
ttypemethod of StreamTokenizer. If the type is equal toTT_WORDthe word counter is increased, and if it is equal toTT_NUMBERthe number counter is increased.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.io.FileReader;
import java.io.StreamTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
int wordCount = 0, numberCount = 0;
StreamTokenizer sTokenizer = new StreamTokenizer(new FileReader("C:/Users/nikos7/Desktop/output.txt"));
while (sTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if (sTokenizer.ttype == StreamTokenizer.TT_WORD) {
wordCount++;
} else if (sTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
numberCount++;
}
}
System.out.println("Words in file : " + wordCount);
System.out.println("Numbers in file : " + numberCount);
}
}
Output:
Words in file : 902
Numbers in file : 72
This was an example of how to count the words and numbers in a File in Java.
