Write a java program to count the characters, words and lines from file.

Here we write a java program which count the number of  characters, words and lines of a given file.The java class name is WordCOunt.java and you have to create a file which should be in the same folder of java class. See the example in below mentioned class.

package com.javaforecast4u;
import java.lang.*;
import java.io.*;
import java.util.*;
class WordCount{
     public static void main(String arg[]) throws Exception
        {
          int char_count=0;
          int word_count=0;
          int line_count=0;
          String s;
          StringTokenizer st;
          BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
          System.out.print("Enter filename : ");
          s=buf.readLine();
          buf=new BufferedReader(new FileReader(s));
          while((s=buf.readLine())!=null)
           {
            line_count++;
            st=new StringTokenizer(s," ,;:.");
            while(st.hasMoreTokens())
             {
               word_count++;
               s=st.nextToken();
               char_count+=s.length();
             }
          }
         System.out.println("Character Count : "+char_count);
         System.out.println("Word Count : "+word_count);
         System.out.println("Line Count : "+line_count);
         buf.close();
        }
}

 Note: the file should be same folder in which java class is there.

7 comments :

  1. I agree with your thoughts!!! As the demand of java programming application keeps on increasing, there is massive demand for java professionals in software development industries. Thus, taking training will assist students to be skilled java developers in leading MNCs.
    Java Training in Chennai

    ReplyDelete