Question:
Write a java program that counts words in a file?
Answer:
Here is an example that counts the words in a file called TheCatInTheHat.txt.
Code:
import java.io.*; import java.util.*; public class WordCount { public static void main(String[] args) throws FileNotFoundException { Map<String, Integer> map = new HashMap<String, Integer>(); Scanner in = new Scanner(new File("TheCatInTheHat.txt")); while (in.hasNext()) { String word = in.next(); word = word.replaceAll("[^a-zA-Z0-9]", ""); word = word.toLowerCase(); if(map.containsKey(word)) { Integer count = (Integer)map.get(word); map.put(word, new Integer(count.intValue() + 1)); } else { map.put(word, new Integer(1)); } } ArrayList arraylist = new ArrayList(map.keySet()); Collections.sort(arraylist); for (int i = 0; i < arraylist.size(); i++) { String key = (String)arraylist.get(i); Integer count = (Integer)map.get(key); System.out.println(key + " : " + count); } } }
Output:
$ java WordCount a : 33 about : 3 after : 1 all : 15 always : 1 and : 69 another : 2 any : 1 are : 5 as : 9 asked : 1 at : 14 away : 6 back : 2 bad : 2 ball : 5 be : 7 bed : 1 bent : 1 bet : 2 big : 5 bit : 3 bite : 1 .......