Java Program to Count the Number of Words in a File

In this tutorial, we are going to see how to write a Java program to count the number of words in a file.

Java Program to Count the Number of Words in a File

public class Main 
   public static void main(String[] args) throws IOException 
      // The input file
      File file = new File("myFile.txt"); 
      // Initialize the array of words
      String[] words = null;    
      // Initializes the counter of word to zero
      int count = 0;     
      // Create the File Reader object
      FileReader fr = new FileReader(file);
      // Create the BufferedReader object
      BufferedReader br = new BufferedReader(fr);    
      String str;
      // Read the contents of the file
      while((str = br.readLine()) != null)    
         // Split the word using space
         words = str.split(" ");   
         // Increment the number of words 
         count = count + words.length;   
      System.out.println("Number of words in the file is:" +count);


Number of words in the file is: 15
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *