保罗,
我建议你通读这个旧线程:Java BufferedReader back to the top of a text file?.
就我个人而言,我更喜欢 Jon Skeet 的回应,它归结为“不要打扰 [除非你必须]。”
干杯。基思。
编辑:即使您遇到异常,您也应该始终关闭该输入文件。该finally
块非常适合此。
编辑2:
希望你还在我们身边。
这是我的尝试,FWIW,你不需要重置输入文件,你只需要转置你的while
和for
循环。
package forums;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordOccurrenceCount
{
public static void main(String[] args) {
try {
String[] words = { "and", "is", "a", "the", "of", "as" };
int[] occurrences = readOccurrences("C:/tmp/prose.txt", words);
for ( int i=0; i<words.length; i++ ) {
System.out.println(words[i] + " " + occurrences[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static final int[] readOccurrences(String filename, String... words)
throws IOException
{
int[] occurrences = new int[words.length];
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
Scanner scanner = new Scanner(reader);
while ( scanner.hasNext() ) {
String word = scanner.next();
for ( int i=0; i<words.length; i++ ) {
if ( words[i].equals(word) ) {
occurrences[i]++;
}
}
}
} finally {
if(reader!=null) reader.close();
}
return occurrences;
}
}
顺便说一句,java.util.Map非常适合构建频率表......并行数组只是 SOOOOO 90 年代。Map 的“默认”实现是HashMap
类......默认情况下,我的意思是在您需要 Map 时使用 HashMap,除非您有充分的理由使用其他东西,这不会经常发生。HashMap 通常是全能表现最好的。