Java Program to Count Words in a File using java.util.Scanner Class

The following code counts the number of words and lines in a file. When you run the program, myFile.txt file is created  with 29 words and 3 lines. Scanner class is used to read the file. By Default, Scanner class uses whitespace  as delimiter to split the words. You can use useDelimiter to set any specified string as a delimiter.  useDelimiter(“\n“)  sets new line as delimiter. You can also use  nextLine() of Scanner class to read line in the file.

package com.javaonline;

import java.util.*;
import java.io.*;
public class CountWordsInFile {
    public static void main(String[] args) throws IOException {
try
{

	String fileName="myFile.txt";

	FileWriter file = new FileWriter(fileName);
	file.write("This program counts the number of words and lines in a file.\n Scanner class is used to read the file.\n It splits the input into tokens using a delimiter.");
	file.close();

     int count =0;
      Scanner sc = new Scanner(new File(fileName));

 //To count words      

      while (sc.hasNext())
          {
    	  count++;
    	  sc.next();
           }

      System.out.println("No of Words in the given file ( " + fileName + " ) : "  + count);

      sc = new Scanner(new File(fileName));

   // To count lines
    //sc.useDelimiter("\n"); //to set new line as delimiter
     // sc.reset(); to use the default delimiter
     count=0;
     while( sc.hasNextLine())
     {
     	 count++;
     	 sc.nextLine();

     }

     System.out.println("No of Lines in the given file ( " + fileName + " ) : "  + count);

      sc.close();

}
catch (FileNotFoundException e)
{
	System.out.println("The given file "+ fileName + "  not found ");
}

    }
}

Running the Program

Output :

count words and lines in a file

 

Reference : Scanner Class in Java 

You may also like

Leave a Reply

Be the First to Comment!