我想在文件中查找关键字。找到关键字后,我想在这个关键字之前得到 50 个单词,在这个关键字之后得到 50 个单词。
我想知道是否有办法以相反的顺序读取文件。
您仍然需要逐行逐字读取文件以找到您要查找的单词...您可以做的是拥有一个包含 50 个单词的缓冲区,例如字符串数组,然后加载您的文本,如果不是您要查找的单词,请将其放入缓冲区中,新单词会覆盖最旧的单词。如果你找到了你需要的东西,从你的缓冲区中取出所有的单词并阅读接下来的 50 个单词。
请使用以下代码。
List<String> previousWords = new ArrayList<String>();
List<String> nextWords = new ArrayList<String>();
boolean foundKeyWord = false;
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("translate.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
boolean b;
while (b = s2.hasNext()) {
String s = s2.next();
if(!foundKeyWord) {
if(s.equals(findKeyWord)) {
foundKeyWord = true;
}
}
//Keyword not found then add to the previouswords list
if(!foundKeyWord) {
previousWords.add(s);
} else {
//already key found now we need to add next 50 words
if(nextWords.size <= 50) {
nextWords.add(s);
} else {
//if 50 key words are added then break from the loop, if in case if there are less than 50 words in file after keyword then scanner will end.
break;
}
}
}
}
//Now we need to fix the previous 50 key words in case if keyword is found after 50th word.
if(previousWords.size > 50){
previousWords.subList(previousWords.size() - 50, previousWords.size());
}