// get the command-line arguments
if (args.length < 2) {
System.out.println("Usage: WordSort inputfile outputfile");
return;
}
String inputfile = args[0];
String outputfile = args[1];
/* Create the word map. Each key is a word and each value is an
* Integer that represents the number of times the word occurs
* in the input file.
*/
Map map = new TreeMap( );
// read every line of the input file
BufferedReader in =
new BufferedReader(new FileReader(inputfile));
String line;
while ((line = in.readLine( )) != null) {
// examine each word on the line
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens( )) {
String word = st.nextToken( );
Object o = map.get(word);
// if there's no entry for this word, add one
if (o == null) map.put(word, new Integer(1));
// otherwise, increment the count for this word
else {
Integer count = (Integer)o;
map.put(word, new Integer(count.intValue( ) + 1));
}
}
}
in.close( );
// get the map's keys and sort them
List keys = new ArrayList(map.keySet( ));
Collections.sort(keys);
// write the results to the output file
PrintWriter out = new PrintWriter(new FileWriter(outputfile));
Iterator iterator = keys.iterator( );
while (iterator.hasNext( )) {
Object key = iterator.next( );
out.println(key + " : " + map.get(key));
}
out.close( );