In this tutorial, we will see the example of 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 of the following, as this program uses them.
Java Program to count the number of words present in a file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | //count the number of words present in a text file import java.io.BufferedReader; import java.io.FileReader; public class CountNoOfWords { public static void main(String[] args) throws Exception { String str; 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); br.close(); } } |
Output:
Number of words present in given file: 72