我想读取一个文件夹中的所有文件,每个文件内容都会被读入一个哈希表。然后我需要将文本文件中的每个单词与每个哈希表进行比较。如果该单词与该哈希表中的任何单词匹配,则变量将以创建该哈希表的相应文件名命名。现在我有两个困难:
1.如何为文件夹中的每个文件创建一个哈希表列表。
2.如何在该哈希表中找到单词时命名变量。
我尝试了这段代码,它适用于 1 个文件、1 个哈希表。
Hashtable HashTableName;
public String namebymatching;
// compare the spannedText for words in each dictionary in folder
public OneExtractor() throws IOException {
super();
// location
HashTableName = new Hashtable();
FilenameFilter ff = new OnlyExt("txt");
File folder = new File("/Folder Path/");
File[] files = folder.listFiles(ff);
Map<String, String> map = new LinkedHashMap<String, String>();
for (int i = 0; i < files.length; i++) {
FileReader fr = new FileReader(files[i].getPath());
BufferedReader reader = new BufferedReader(fr);
String st = "", str = " ";
while ((st = reader.readLine()) != null) {
str += st + " ";
}
map.put(files[i].getName(), str);
}
Set set = map.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(
"/Folder Path"+me.getKey()));
} catch (FileNotFoundException ex) {
Logger.getLogger(PersonExtractor.class.getName()).log(Level.SEVERE, null, ex);
}
try {
String line = br.readLine();
HashTableName.put(line.toLowerCase(), 1);
while (line != null) {
line = br.readLine();
if (!line.isEmpty())
HashTableName.put(line.toLowerCase(), 1);
}
} catch (Exception ex) {
} finally {
try {
br.close();
} catch (IOException ex) {
Logger.getLogger(PersonExtractor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private boolean isHashTableName(String s) {
return HashTableName.containsKey(s.toLowerCase());
}
///Extension
public static class OnlyExt implements FilenameFilter {
String ext;
public OnlyExt(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
// Find word match :
String word = //some function here to extract word;
namebymatching = "NOT" + filename; //filename should be here
if (isHashTableName(spannedText))
namebymatching = "ISPARTOF" +filename;//filename should be here