Java Program to Search a Particular Word in a File

In this tutorial, you will learn how to Search for a Particular Word in a File in java. To understand it better, you may want to check the following first:


Java Program to Search a Particular Word in a File

First, save the content in a text file with the same name that you enter in a program. For this example, a text file saved with the name javaCode.txt

javaCode.txt

Welcome to Simple2Code.
Let Start
first tutorial
second Program

Source Code:

//search the particular word in a file 

 import java.io.*;

 public class SearchWord
 {
  public static void main(String[] args) throws IOException 
  {
      File f = new File("javaCode.txt"); //file
      String[] words=null;  //Intialization
      
      FileReader fr = new FileReader(f);  //File Reader object
      BufferedReader br = new BufferedReader(fr); 
      
      String s;     
      String input="program";
      int count=0;   //Intializing count
      
      while((s = br.readLine())!=null) //Reading Content from the file
      {
        words=s.split(" ");  //Split the word using space
          for (String word : words) 
          {
            if (word.equals(input))  //Search for the given word
            {
              count++;    //If Present increase the count by one
            }
          }
      }
      if(count!=0)  //Check for count not equal to zero
      {
        System.out.println("Number of times given word present: "+count);
      }
      else
      {
        System.out.println("The given word is not present.");
      }
      
        fr.close();
  }
 }

Output:

Number of times given word present: 3