Count Number of Words in a file stored at any location
SOURCE : CountWordsInFile.javaimport 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); }} INPUTstore any file and give location of file for eg. I have used this location for file C:\\new\\testing.txtOUTPUT
{all=1, are=1, and=1, this=1, is=1, my=2, india=1, indian=1}

0 comments :
Post a Comment