This is the second solution to count the number of occurrences of a given string in the file. This approach uses the FileReader, Scanner, and String class methods.
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class SearchForAWord {
//The static variable wordCnt to keep track of matches
static int wordCnt;
public static void main(String[] args) throws IOException {
FileReader fRead=new FileReader("C:\\Users\\Nagendra\\sample.txt");
Scanner scanFile = new Scanner(fRead);
/* Display the sample file contents to the console using the
Scanner and FileReader */
System.out.println("The contents of the file are below");
System.out.println();
while (scanFile.hasNextLine())
System.out.println(scanFile.nextLine());
scanFile.close();
/* Re-open the same sample file using Scanner and FileReader,
to search and count for a given word in further steps. */
FileReader fileRead=new FileReader("C:\\Users\\Nagendra\\sample.txt");
@SuppressWarnings("resource")
Scanner scanFile1 = new Scanner(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();
// Read line by line and call the function parseEachLine().
while (scanFile1.hasNextLine())
parseEachLine(scanFile1.nextLine(),strToSrch);
System.out.println("The word="+strToSrch+" appearing "+wordCnt+" number of times in a give file");
inpStr.close();
}
private static void parseEachLine(String lineRd,String strSrch) {
//Split the line with delimiter space, into an array of strings
String [] words;
words = lineRd.split(" ");
// Compare the given string, with each word in the array
for (String word: words) {
if (word.equalsIgnoreCase(strSrch))
wordCnt++;
}
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