Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

Hot Searches
struts-config.xml  web.xml  Java date format  read/write text file using javascript  ArrayList  Insert Data into Database Using Hibernat  create text file using java  insert data to text file using java  Visual Basic Date and Time Display the t  Create table and insert data by sql quer 

  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Java Word Count - Word Count Example in Java

                         

This example illustrates how to count the number of lines, number of words and number of characters in the specified file. Program takes the file name as parameter and it counts the number of words and lines present in the file. Parameter is optional and if you simply run the program without mentioning the file name then you will have to input some strings and program will count the number of characters and number of words for your given strings. This topic is related to the I/O (input/output) of java.io package.

In this example we are using FileReader class of java.io package. The File class is an abstract representation of file and directory pathnames. 

Explanation

This program counts the number of lines, number of words and number of characters in the specified file. We will be declaring two functions called wordcount and linecount in the program. The function linecount has been overloaded according to the passing argument. If you input contents through the file then linecount function will be called (If specified file exists) otherwise main function counts the number of characters and number of lines (always, the number of line will be only 1 in this condition) itself but for the counting of the number of words by using the wordcount function.

wordcount(String line)

The function wordcount(String line) takes either the content of the specified file or arguments passed with the run command for a java program as parameter 'String line'. The wordcount() function is using arrayname.charAt(index) to find position of space in the string.  A counter variable 'numWords' is used to count the number of words.

linecount(String fileName);

The function linecount(String fileName) takes the specified file name as a string parameter and create a instance for the FileReader class to buffering then the file or string and it is passed to the function linecount(String fName, BufferedReader in).

linecount(String fileName, BufferedReader);

The function linecount(String fName, BufferedReader in) takes the specified file name and created instance in for the BufferedReader class by calling function linecount(String fileName) and assign the content of the buffer in a string variable line. And then the function linecount(String fileName, BufferedReader) counts and print the number of characters, number of lines. To count the number of words call the wordcount(String line) function.

Code of the Program : 

import java.io.*;

public class  WordCount{
  private static void linecount(String fName, BufferedReader in) throws IOException{
  long numChar = 0;
  long numLine=0;
  long numWords = 0;
  String line;
 
   do{
      line = in.readLine();
      if (line != null){
        numChar += line.length();
 
       numWords += wordcount(line);
        numLine++;
      }
    }
while(line != null);
    System.out.println("
File Name: " + fName);
    System.out.println("
Number of characters: " + numChar);
    System.out.println("Number of words: " + numWords);
    System.out.println("Number of Lines: " + numLine);
  }

  private static void linecount(String fileName){
    BufferedReader in =
 null;
    
try{
      FileReader fileReader = 
new FileReader(fileName);
      in = 
new BufferedReader(fileReader);
      linecount(fileName,in);
    }
    
catch(IOException e){
      e.printStackTrace();
    }
  }
  private static long wordcount(String line){
    
long numWords = 0;
    int index = 0;
    boolean prevWhiteSpace = true;
    while(index < line.length()){
 
     char c = line.charAt(index++);
      boolean currWhiteSpace = Character.isWhitespace(c);
     
 if(prevWhiteSpace && !currWhiteSpace){
        numWords++;
      }
      prevWhiteSpace = currWhiteSpace;
    }
   
 return numWords;
  }
  public static void main(String[] args){
  
  long numChar = 0;
 
   long numLine=0;
    String line;
    try{
      if (args.length == 0)
      {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        line = in.readLine();
        numChar = line.length();
       
 if (numChar != 0){
          numLine=1;
        }
        System.out.println(
"Number of characters: " + numChar);
        System.out.println("Number of words: " + wordcount(line));
        System.out.println("Number of lines: " + numLine);
      }else{
        for(int i = 0; i < args.length; i++){
          linecount(args[i]);
        }
      }
    }
    catch(IOException e){
      e.printStackTrace();
    }
  }
}

Download Word count Example

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

4 comments so far (
post your own) View All Comments Latest 10 Comments:

sir please give me
w.a.p in a c program count the number of lines words characters in the given input
and important programs list give me
iam studying in m.c.a in A.N.U
please give me please give me
.........
thankyou sir
bye

Posted by neeraja.s on Wednesday, 12.17.08 @ 08:13am | #82876

I am very impressed by the way you simplify your codes.
Keep it up

Posted by Kasingye Emmanuel on Monday, 08.20.07 @ 19:41pm | #23796

This is a great beauty. My utmost thanks.

Posted by Kimtran on Wednesday, 06.13.07 @ 11:09am | #19087

this example is too good,even all materials also too good

Posted by kalyan on Friday, 04.27.07 @ 15:48pm | #15009

Tell A Friend
Your Friend Name

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.