+92 332 4229 857 99ProjectIdeas@Gmail.com

How to count words and characters in file (Java)


How to count words and characters in file (Java):

The following code shows you how to count words and characters in file and also shows you how to display the file length on bytes. For counting words strategy is that: reading a file line by line and using string split function spit the line at every space and count the new splitted array length excluding of spaces. For reading characters in file strategy is that: reading a file line by line and count the each length of line.


Code

import java.io.*;

public class Test {

   public static void main(String[] args) {
     
     try {
          

         int countWords = 0 , countChar = 0;               

         File f = new File("D:\\abc.txt");                                      

         FileReader fr = new FileReader(f);                    

         BufferedReader br = new BufferedReader(fr);                   

         String line = br.readLine();
         String[] str;                   

              while ( line != null ) {                     

                  // Splitting the line at every space.                        

                     str = line.split(" ");

                 // now in str, all the words excluding of space and count them

                     countWords += str.length;

                     countChar += line.length();

                     line = br.readLine();                        

              }

       System.out.println("The Number Of Words In File Are : " + countWords);

       System.out.println("The Number Of Characters In File Are : " + countChar);

       System.out.println("The Number Of Bytes In File Are : " + f.length());

                   

    } catch (Exception e) {

         System.out.println(e);

    }             
  }                 
}

0 comments: