Java Program to Count the Number of Words Present in a text file

In this tutorial, we will see the example of how to count the number of words present in a text file in java.

First, create a text file with any name you like. In this example, inputInfo.txt is the file name. Then insert some sentences in that text file. The following java code will count the number of words present in that file.

Before we start, it is important that you have an idea of the following, as this program uses them.


Java Program to count the number of words present in a file

//count the number of words present in a text file 

 import java.io.BufferedReader;  
 import java.io.FileReader;  
   
 public class CountNoOfWords
 {  
    public static void main(String[] args) throws Exception 
    {  
    String str;  
    int count = 0;  

    //file in read mode  
    FileReader f = new FileReader("inputInfo.txt ");  
    BufferedReader br = new BufferedReader(f);  

  
    while((str= br.readLine()) != null) 
    {  
      //Splits into words  
      String words[] = str.split(""); 

      //Counts each word  
      count = count + words.length;  

    }  

    System.out.println("Number of words present in given file: " + count);  
    br.close();  
    }  
 }

Output:

Number of words present in given file: 72