How to find if a string is present in a text file?

How to find if a string is present in a text file?

Example:

Input:  file - Java is the programming langualge.
Java is the programming langualge.
Output: Number of occurrences of Java is 2

Approach

Java


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FindingWordInFile {
    public static void main(String[] args) {
        String word = "Java";
        int count = findWord(word);

        if (count > 0) {
            System.out.println("File contains the specified word");
            System.out.println("Number of occurrences is: " + count);
        } else {
            System.out.println("File does not contain the specified word");
        }
    }

    private static int findWord(String word) {
        int count = 0;
        // Reading the contents of the file
        Scanner sc2 = null;
        try {
            sc2 = new Scanner(new FileInputStream("D:\\file.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (sc2.hasNextLine()) {
            String line = sc2.nextLine();
            System.out.println(line);
            if (line.indexOf(word) != -1) {
                count = count + 1;
            }
        }
        sc2.close();
        return count;
    }
}


No comments:

Post a Comment