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 ttype method of StreamTokenizer. If the type is equal to TT_WORD the word counter is increased, and if it is equal to TT_NUMBER the 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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button