How to count the number of words in a text file using Java?


Read the number of words in text file

  • Create a FileInputStream object by passing the required file (object) as a parameter to its constructor.
  • Read the contents of the file using the read() method into a byte array.
  •  Insatiate a String class by passing the byte array to its constructor.
  • Using split() method read the words of the String to an array.
  • Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.

Example

import java.io.File;
import java.io.FileInputStream;
public class Sample {
   public static void main(String args[]) throws Exception{

      int count =0;
      File file = new File("data");
      FileInputStream fis = new FileInputStream(file);
      byte[] bytesArray = new byte[(int)file.length()];
      fis.read(bytesArray);
      String s = new String(bytesArray);
      String [] data = s.split(" ");
      for (int i=0; i<data.length; i++) {
         count++;
      }
      System.out.println("Number of characters in the given file are " +count);
   }
}

Output

Number of characters in the given String are 4


Updated on: 20-Feb-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements