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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | //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