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






Using StreamTokenizer to count words and numbers in a file

 


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);

  }
}

   
  








Related examples in the same category

1.Create StreamTokenizer from BufferedReader
2.Create StreamTokenizer from FileReader
3.Extract Tokens with StreamTokenizer
4.Read file with StreamTokenizer
5.Set whitespaceChars
6.Set eolIsSignificant
7.Deal with StreamTokenizer.TT_WORD, StreamTokenizer.TT_NUMBER
8.Tokenizing Java Source Code
9.Stream Token