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
- Read file line by line
- Split into words and compare
- Consider case sensitivity
Related File I/O exercises
- Practice Check File Exists in Java
- Practice Count Words in File in Java
- Practice Reverse File Lines in Java
Practice all File I/O exercises · Run this idea in the Java compiler