In this tutorial, we will see the example on how to count the number of words present in a text file in java.
First, create a text file with any name you like. In this example, inputInfo.txt is the file name. Then insert some sentences in that text file. The following java code will count the number of words present in that file.
Before we start, it is important that you have an idea on the following, as this program uses them.
Example: Java Program to count the number of words present in a file.
//count the number of words present in a text file
public class CountNoOfWords
public static void main(String args) throws Exception
int count = 0;
//file in read mode
FileReader f = new FileReader("inputInfo.txt ");
BufferedReader br = new BufferedReader(f);
while((str= br.readLine()) != null)
//Splits into words
String words = str.split("");
//Counts each word
count = count + words.length;
System.out.println("Number of words present in given file: " + count);
Number of words present in given file: 72