In this tutorial, you will learn how to Count the Number of Words in a File in java. To understand it better, you may want to check the following first:
Java Program to Count the Number of Words in a File
First, save the content in a text file with the same name that you enter in a program.
For this example, a text file saved with the name javaCode.txt
javaCode.txt
Welcome to Simple2Code.
Let Start
first tutorial
second Program
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 | //count number of words in a file import java.io.*; public class WordCount { public static void main(String[] args) throws IOException { File f = new File("javaCode.txt"); //creating txt file String[] words=null; //Intializing int wordCount = 0; //Intializing word count FileReader fr = new FileReader(f); //Creation of File Reader object BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object String s; while((s = br.readLine())!=null) //Reading Content from the file { words = s.split(" "); //Split the word using space wordCount = wordCount + words.length; //increment in word count for each word } fr.close(); System.out.println("Number of words in the file:" +wordCount); //Display } } |
Output:
Number of words in the file:9