我曾尝试创建一个程序,它将读取特定目录中的多个文本文件,然后生成所有文本文件中出现的单词的频率。
这是我运行它们的类。
例如
文本文件1:hello my name is john hello my
文本文件2:the weather is nice the weather is
输出将显示
hello 2
my 2
name 1
is 3
john 1
the 2
weather 2
nice 1
我遇到的问题是,我的程序一运行就立即终止,根本没有任何输出。
这是我的类
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class WordCountstackquestion implements Runnable {
public String filename;
public WordCountstackquestion(String filename) {
this.filename = filename;
}
public void run() {
File file = new File("C:\\Users\\User\\Desktop\\files\\1.txt");
if (file.isDirectory()) {
Scanner in = null;
for (File files : file.listFiles()) {
int count = 0;
try {
HashMap<String, Integer> map = new HashMap<String, Integer>();
in = new Scanner(file);
while (in.hasNext()) {
String word = in.next();
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
}
else {
map.put(word, 1);
}
count++;
}
System.out.println(file + " : " + count);
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
} catch (FileNotFoundException e) {
System.out.println(file + " was not found.");
}
}
}
//in.close();
}
}
这是我运行它们的类。
public class Mainstackquestion {
public static void main(String args[]) {
if (args.length > 0) {
for (String filename : args) {
CheckFile(filename);
}
}
else {
CheckFile("C:\\Users\\User\\Desktop\\files\\1.txt");
}
}
private static void CheckFile(String file) {
Runnable tester = new WordCountstackquestion(file);
Thread t = new Thread(tester);
t.start();
}
}