Java Program to find and count a specific word in a Text File

Hey everyone! In this article, we will learn how to find a specific word in a text file and count the number of occurrences of that word in the text file. Before taking a look at the code, let us learn about BufferedReader class and FileReader class.

FileReader class in Java


FileReader class is used for file handling purposes in Java. It reads the contents of a file in a stream of characters. It is present in the java.io package. It reads the contents into a character array.

FileReader fr = new FileReader(“filename.txt”);

BufferedReader class in Java


The BufferedReader class in Java is used to read contents from a file in Java. It is used to read text from the input stream in Java. It is present in the java.io.BufferedReader package in Java. It buffers the character read into an array.

BufferedReader bfr = new BufferedReader(fr);

Java Program to find a specific word in a text file and print its count.


import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;


public class Program 
{
   public static void main(String[] args) throws Exception 
   {
      int cnt=0;
      String s;
      String[] buffer; 
      File f1=new File("file1.txt"); 
      FileReader fr = new FileReader(f1);
      BufferedReader bfr = new BufferedReader(fr);
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the word to be Searched");
      String wrd=sc.nextLine();
       
           

      while((s=bfr.readLine())!=null)   
      {
         buffer=s.split(" ");  
          for (String chr : buffer) 
          {
                 if (chr.equals(wrd))   
                 {
                   cnt++;    
                 }
          }
      }
      if(cnt==0)  
      {
         System.out.println("Word not found!");
      }
      else
      {
         System.out.println("Word : "+wrd+"found! Count : "+cnt);
      }
      
         fr.close();
   }


}
Output:-

Enter the word to be Searched krishna
Word : krishnafound! Count : 4

 

I hope this article was useful to you!
Please leave a comment down below for any doubt/suggestion.

Also read: QR Code to Text converter in Java

Leave a Reply

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