Count Number of Words in a file stored at any location

Count Number of Words in a file stored at any location
SOURCE : CountWordsInFile.java


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

public class CountWordsInFile {

public static void main(String args[]) throws IOException {

// creating buffer

BufferedReader br = new BufferedReader(new FileReader(
"C:\\new\\testing.txt"));

// Creating the Map to store the words and their occurrences

HashMap frequencyMap = new HashMap();

String currentLine = null;

// Reading line by line from the text file
while ((currentLine = br.readLine()) != null) {

// Parsing the words from each line
StringTokenizer st = new StringTokenizer(currentLine,
" \t\n\r\f.,;:!?'\"");
while (st.hasMoreTokens()) {
String currentWord = st.nextToken();

Integer frequency = frequencyMap.get(currentWord.toLowerCase());
/*
* if(frequency == null){ frequency = 0; } //Putting each word
* and its occurrence into Map
*/frequencyMap.put(currentWord.toLowerCase(),
(frequency == null ? 1 : frequency + 1));
}

}

// Displaying the Result
System.out.println(frequencyMap);

}

}



INPUT

store any file and give location of file
for eg. I have used this location for file C:\\new\\testing.txt




OUTPUT


{all=1, are=1, and=1, this=1, is=1, my=2, india=1, indian=1}







Sandeep Kumar D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Sandeep Kumar D

Follow Me @Google+




SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment