java

How to Count the Number of Occurrences of a Word in a File in Java

In this tutorial, we are going to see how to count the number of occurrences of a word in a file in Java.
 

Program to Count the Number of Occurrences of a Word in a File
import java.io.*;

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;  
		// Create the File Reader object
		FileReader fr = new FileReader(file);
		// Create the BufferedReader object
		BufferedReader br = new BufferedReader(fr);  
		String str;     
		// Word to search
		String search = "Learn";   
		// Initializes the counter of word to zero
		int count = 0;    
		// Read the contents of the file
		while((str = br.readLine()) != null)  
		{
			// Split the word using space
			words = str.split(" ");  
			for (String word : words) 
			{
				//Search for the word
				if (word.equals(search))   
				{
					// If present, increment the counter
					count++;    
				}
			}
		}
		if(count!=0) 
		{
			System.out.println("The word is present "+ count + " times in the file");
		}
		else
		{
			System.out.println("The word doesn't exist in the file!");
		} 
		fr.close();
   }
}

Output:

The word is present 3 times in the file
[st_adsense] 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 *