java文件从文档中间读取反向顺序

时间:2012-04-11 07:22:19

标签: java file-io

我想在文件中找到关键字。找到关键字后,我希望在此关键字之前获得50个字,在此关键字之后获得50个字。

我想知道是否有办法以相反的顺序读取文件。

2 个答案:

答案 0 :(得分:1)

您仍然需要逐行读取文件以找到您要查找的单词...您可以做的是拥有一个包含50个单词的缓冲区,如String数组然后,加载您的文本,如果它不是您要查找的单词,请将其放入缓冲区,新单词将覆盖最旧的单词。如果您找到了所需内容,请从缓冲区中获取所有单词并阅读下一个单词。

答案 1 :(得分:0)

请使用以下代码。

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());
  }