Following progrm used to read the file and found the number of words.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordCountFromFile {
public static void main(String[] args) {
String filePath = "input.txt"; // Replace with your file path
int wordCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
// Split the line into words based on whitespace
String[] words = line.trim().split("\\s+");
wordCount += words.length;
}
System.out.println("Total number of words in the file: " + wordCount);
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
Explanation: As part of this program, we initialize the filePath variable with "input.txt" to read the file from the current directory, and we initialize the wordCount variable to 0.
Next, we create a BufferedReader object using the line:
BufferedReader reader = new BufferedReader(new FileReader(filePath))
This sets up the reader to read the file line by line.
We then declare a String variable named line to hold each line read from the file. Using the following loop:
while ((line = reader.readLine()) != null)
we read the file line by line until the end of the file (when readLine() returns null).
Inside the loop, we trim the line to remove leading and trailing whitespace, then split the line into words using the regular expression \\s+:
String[] words = line.trim().split("\\s+");
This expression splits the line based on one or more whitespace characters (spaces, tabs, etc.).
We then increment the wordCount by the number of words in the current line:
wordCount += words.length
Finally, after the loop is finished, we print the total word count using:
System.out.println(“Total number of words in the file: ” + wordCount);