-1

ファイル内のキーワードを検索したい。キーワードを見つけた後、このキーワードの前に 50 単語、このキーワードの後に​​ 50 単語を取得したいと考えています。

ファイルを逆順に読む方法はあるのだろうか。

4

2 に答える 2

1

探している単語を見つけるには、ファイルを行ごと、単語ごとに読み取る必要があります...できることは、文字列配列のように50単語を保持するバッファを用意してから、テキストをロードすることです探している単語でない場合は、新しい単語で古い単語を上書きして、バッファにスローします。必要なものが見つかったら、バッファからすべての単語を取得し、次の 50 を読み取ります。

于 2012-04-11T07:28:40.120 に答える
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());
  }
于 2012-04-11T08:00:55.797 に答える