Search in File in Java: Explanation & Practice

Search for a word in file and count occurrences

Problem summary

Count how many times a specific word appears in a file.

Starter code

import java.io.*;

public class Main {
    public static void main(String[] args) {
        String searchWord = "the"; // Test case 1
        
        // Count occurrences in file
        // Print: Found <count> times
    }
}

Expected output and test cases

  • 'the' found 5 times
    Found 5 times
  • Word not found
    Found 0 times
  • Common word
    Found 12 times

Hints

  1. Read file line by line
  2. Split into words and compare
  3. Consider case sensitivity

Related File I/O exercises

Practice all File I/O exercises · Run this idea in the Java compiler