我一直在尝试很多事情。目前,我有这个功能供我阅读
private void readFile(File file) throws FileNotFoundException, IOException{
//StringBuilder fileContents = new StringBuilder();
BufferedReader bufferread = new BufferedReader(new FileReader(file));
String text;
int i=1;
while ((text = bufferread.readLine()) != null) {
//fileContents.append(text);
//fileContents.append("\n");
String[] tokens = text.split(" ");
Line line = new Line(i,text);
for(String token:tokens) {
tokens[i]=tokens[i].replaceAll("[^a-zA-Z]", "");
}
i++;
//for loop to go through tokens array
for(String token:tokens) {
if(myMap.containsKey())
{
List<Line> count = myMap.get();
count.add(line);
}
else{
myMap.put(, );
}
i++;
}
}
}
我的程序是一个gui,可让您用1个按钮读取文件。然后您可以在右下角在txt文件中搜索一个单词。然后输入一个单词并按search后,它会显示行号和该单词所在的所有行。我发布此问题是因为我很难弄清楚如何将我的行存储在哈希图中。我有一个Line.java类,所以我只需要每个循环部分的帮助。我的第一个循环和第二个我肯定可以合并。我的第二个大都是错的。
一些变量(我有一些用于此类内容的类,我只需要帮助将行存储在HashMap中)
String userSearchTerm = " ";
SimpleMap<String, List<Line>> myMap = new HashMapBackedSimpleMap<>();
我想在选择文件按钮上按一下,以读取文件,按行标记化,然后存储在我的HashMap中。但是目前它没有这样做。
最佳答案
我最终找到了一个好方法
int i = 1;
while ((text = bufferread.readLine()) != null) {
//fileContents.append(text);
//fileContents.append("\n");
String[] tokens = text.split(" ");
Line line = new Line(i, text);
//for loop to go through tokens array
for (String token : tokens) {
token = token.replaceAll("[^a-zA-Z]", "");
if (myMap.get(token) != null) {
List<Line> count = myMap.get(token);
if(!count.contains(line)){
count.add(line);
myMap.put(token, count);
}
} else {
List<Line> lines= new ArrayList<Line>();
lines.add(line);
myMap.put(token,lines);
}
i++;
}
}
}
关于java - Java程序读取文件,标记行,然后将它们存储在 HashMap 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59167354/