//version by wlfshmn import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.TreeMap; import java.util.HashMap; public final class WordCount2 { //counts the words in a text file... private static final Map dictionary = new HashMap(50000); private static int tWords = 0; private static int tLines = 0; private static long tBytes = 0; public static void main(final String[] args) throws Exception { System.out.println("Lines\tWords\tBytes\tFile\n"); //TIME STARTS HERE final long start = System.currentTimeMillis(); for (String arg : args) { final File file = new File(arg); if (!file.isFile()) { continue; } int l_cnt = 0; int w_cnt = 0; final int numBytes = (int) file.length(); byte[] content = new byte[numBytes]; int totalread = 0; while (totalread != numBytes) { InputStream is = null; try { is = new FileInputStream(arg); totalread += is.read(content, totalread, numBytes - totalread); } catch (IOException e) { if (is != null) { is.close(); } } } boolean inword = false; int wstart = 0; for (int i = 0; i < content.length; i++) { char c = (char) content[i]; if (c == '\n') { ++l_cnt; } else if (c >= '0' && c <= '9') { } else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { if (!inword) { wstart = i; inword = true; ++w_cnt; } } else if (inword) { countWord(new String(content, wstart, i - wstart)); inword = false; } } if (inword) { countWord(new String(content, wstart, content.length - wstart)); } System.out.println(l_cnt + "\t" + w_cnt + "\t" + numBytes + "\t" + arg); tLines += l_cnt; tWords += w_cnt; tBytes += numBytes; } //only converting it to TreepMap so the result appear ordered, I could have //moved this part down to printing phase (i.e. not include it in time). TreeMap sort = new TreeMap (dictionary); //TIME ENDS HERE final long end = System.currentTimeMillis(); System.out.println("---------------------------------------"); if (args.length > 1) { System.out.println(tLines + "\t" + tWords + "\t" + tBytes + "\tTotal"); System.out.println("---------------------------------------"); } for (Map.Entry pairs : sort.entrySet()) { System.out.println(pairs.getValue()[0] + "\t" + pairs.getKey()); } System.out.println("Time: " + (end - start) + " ms"); } private static void countWord(String word) { int[] count = dictionary.get(word); if (count != null) { count[0]++; } else { dictionary.put(word, new int[]{1}); } } }