Using StreamTokenizer to count words and numbers in a file : StreamTokenizer « File « Java Tutorial






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("yourFile.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("Number of words in file: " + wordCount);
    System.out.println("Number of numbers in file: " + numberCount);

  }
}








11.74.StreamTokenizer
11.74.1.Using StreamTokenizer to count words and numbers in a file
11.74.2.Tokenizing Java Source Code