Count Words in File in Java: Explanation & Practice
Count total words in a file
Problem summary
Write a program that counts all words in a text file.
Starter code
import java.io.*;
public class Main {
public static void main(String[] args) {
// Count words in file
// Print: Word count: <count>
}
}Expected output and test cases
- 10 words in file
Word count: 10
- Larger file
Word count: 100
- Empty file
Word count: 0
Hints
- Split each line by whitespace
- Sum word counts from all lines
- Handle empty lines
Related File I/O exercises
Practice all File I/O exercises · Run this idea in the Java compiler