public class WordSort {
public static void main(String[] args) throws IOException {
// 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 HashMap();
// 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);
// Now 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();
}
}
如果輸入檔 Ian Moore.txt 的內容如下:
Well it was my love that kept you going
Kept you strong enough to fall
And it was my heart you were breaking
When he hurt your pride
So how does it feel
How does it feel
How does it feel
How does it feel
你可以用下面的方式來執行:
java WordSort "Ian Moore.txt" count.txt
執行完後的結果存在 count.txt 檔中,內容如下:
And : 1
How : 3
Kept : 1
So : 1
Well : 1
When : 1
breaking : 1
does : 4
enough : 1
fall : 1
feel : 4
going : 1
he : 1
heart : 1
how : 1
hurt : 1
It : 6
kept : 1
love : 1
my : 2
pride : 1
strong : 1
that : 1
to : 1
was : 2
were : 1
you : 3
your : 1
public void printElements(Collection c, PrintStream out) {