Java Program to count the number of words in a String



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. Instantiate 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



Advertisements