This is the first solution to count the number of occurrences of a given word in the file. This approach uses the FileReader, BufferedReader, and string buffer methods.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class SearchAWordAndCount {
//The static variable wordCnt to keep track of word count
public static int wordCnt;
public static void main(String[] args) throws IOException {
FileReader fRead=new FileReader("C:\\Users\\Nagendra\\sample.txt");
@SuppressWarnings("resource")
BufferedReader fileToRd = new BufferedReader(fRead);
String lineRead;
/* Display the sample file contents to the console using the
BufferedReader and FileReader */
System.out.println("The contents of the file are below");
System.out.println();
while ((lineRead= fileToRd.readLine()) != null)
System.out.println(lineRead);
fileToRd.close();
/* Re-open the same sample file using BufferedReader and FileReader,
to search and count for a given word in further steps. */
FileReader fileRead=new FileReader("C:\\Users\\Nagendra\\sample.txt");
@SuppressWarnings("resource")
BufferedReader fileToRead = new BufferedReader(fileRead);
System.out.println();
Scanner inpStr=new Scanner(System.in);
System.out.println("Enter the String to be searched and counted in the given file");
String strToSrch=inpStr.next();
StringBuffer lineReadBuff= new StringBuffer();
/* Read line by line and search for the given word in each line,
* using the string buffer methods. Call the function parseEachLine().
*/
while ((lineRead= fileToRead.readLine()) != null) {
lineReadBuff.append(lineRead);
parseEachLine(lineReadBuff,strToSrch);
}
System.out.println("The word="+strToSrch+" appearing "+wordCnt+" number of times in a give file");
inpStr.close();
}
private static void parseEachLine(StringBuffer lineRd,String strSrch) {
int startIndex=0,foundIndex=0;
/* Search for the give work in each line multiple times
* with the help of the indexOf method, and increment wordCnt.
*/
while (foundIndex != -1) {
foundIndex=lineRd.indexOf(strSrch,startIndex);
if (foundIndex != -1) {
wordCnt++;
startIndex=foundIndex+strSrch.length();
}
}
//After each line processed, clear the string buffer
lineRd.delete(0, lineRd.length());
return;
}
}
OUTPUT:
The contents of the file are below
This line one with java word existing.
This is second line has no such word.
Third line java by default available.
java and java repeated twice in the fourth line.
Enter the String to be searched and counted in the given file
java
The word=java appearing 4 number of times in a give file

Leave a comment