Java Program to count the number of words in a String

Java 8Object Oriented ProgrammingProgramming

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.


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()];;
      String s = new String(bytesArray);
      String [] data = s.split(" ");
      for (int i=0; i<data.length; i++){
      System.out.println("Number of characters in the given file are " +count);


Number of characters in the given String are 4

Published on 12-Feb-2018 11:00:36