Home Tutorial Java Core Files Java count words from file

 
 

Share on Google+Share on Google+
Java count words from file
Posted on: June 12, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to determine the number of words present in the file.

Java count words from file

In this section, you will learn how to determine the number of words present in the file.

Explanation:

Java has provides several useful classes and methods which has really made the programming easier. Here by using the StringTokenizer class, we can easily count the number of words from the file. You can see in the given example, we have initialized a counter to 0 and read the whole file by using BufferedReader class. The data is stored into the string which is then break into tokens. Then using the while loop, we have checked if there are more tokens available in the string tokenizer, then return the token and increment the counter. Finally this counter value returns the number of words.

StringTokenizer: This class break a string into tokens.

hasMoreTokens(): This method of StringTokenizer class tests if there are more tokens available from this tokenizer's string.

nextToken():  This method of StringTokenizer class returns the next token in this string tokenizer's string.

Here is the file.txt:

Hello World

All glitters are not gold.
Truth is better than facts.
A man is not old until regrets take the place of dreams. 

Here is the code:

import java.io.*;
import java.util.*;

public class FileCountwords {
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
		String line = "", str = "";
		int count = 0;
		while ((line = br.readLine()) != null) {
			str += line + " ";
		}
		StringTokenizer st = new StringTokenizer(str);
		while (st.hasMoreTokens()) {
			String s = st.nextToken();
			count++;
		}
		System.out.println("File has " + count + " words.");
	}

}

Output:

File has 24 words.
Advertisement

Related Tags for Java count words from file:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 12, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com