Java count words from file


 

Java count words from file

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

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.

Ads