3:11 pm - Tuesday November 23, 6523

Java Example Program to count number of words in a file

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

/**
*@author:candidjava.com
*@description:To find number of words in a file
*/

import java.io.FileReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;

class NumberWords {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("c:/test.txt");
BufferedReader br = new BufferedReader(fr);
String line = "", str = "";
int a = 0;
int b = 0;
while ((line = br.readLine()) != null) {
str += line + " ";
b++;
}
System.out.println("Totally " + b + " lines");

System.out.println(str);

StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String s = st.nextToken();
a++;
}
System.out.println("File has " + a + " words are in the file");
}

}


OUTPUT:
Totally 6 lines
hi hello               how are you?    when will you come here?
File has 10 words are in the file

Filed in: Z-A All Java Codes

Comments are closed.