【发布时间】:2011-08-09 01:19:59
【问题描述】:
一项家庭作业要求我实现一个程序,该程序通过为每个文件启动一个新线程来计算一个或多个文件中的单词(文件名被指定为命令行上的参数)。
这是我的问题:run() 方法不能抛出 IOException,因为 Runnable 接口中的 run() 方法不会抛出 IOException。通过将 File 和 Scanner 构造函数调用放在实现 Runnable 的类的构造函数中,我已经绕过了编译器的警告,但即使它现在编译得很好,我仍然不知何故感到阴暗,就像我在做一些不洁之事。有什么想法吗?
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
public class WordCounter implements Runnable {
File inFile;
Scanner in;
int characters;
int words;
int lines;
int[] counted;
public WordCounter(String aFile) throws FileNotFoundException {
inFile = new File(aFile);
in = new Scanner(inFile);
counted = new int[3];
}
public int[] getTotals() {
return counted;
}
public void run() {
characters = 0;
words = 0;
lines = 0;
while (in.hasNextLine()) {
String thisLine = in.nextLine();
lines++;
Scanner line = new Scanner(thisLine);
while (line.hasNext()) {
String thisWord = line.next();
words++;
characters++; // because each call to line.next() strips a whitespace character
Scanner word = new Scanner(thisWord);
word.useDelimiter("");
while (word.hasNext()) {
char ch = word.next().charAt(0);
characters++;
}
}
}
counted[0] = characters;
counted[1] = words;
counted[2] = lines;
}
}
【问题讨论】:
标签: java multithreading ioexception