2012-04-11 48 views
-1

我想在文件中查找關鍵字。找到關鍵字後,我希望在此關鍵字之前獲得50個字,並在此關鍵字之後獲得50個字。java文件從文檔中間讀取反向順序

我不知道是否有一種方式來讀取文件以相反的順序。

+2

我不知道你是否嘗試過任何東西! – vikiiii 2012-04-11 07:24:53

+0

有很多方法,首先嚐試自己,然後發佈問題,如果出現問題。 – 2012-04-11 07:28:33

回答

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

你仍然需要逐行逐字閱讀文件以找到你正在尋找的單詞...你可以做的是讓一個緩衝區保存50個字,就像一個字符串數組,然後,加載你的文本,如果它不是你正在尋找的單詞,把它放到緩衝區中,用新單詞覆蓋最老的單詞。如果你找到你需要的,從你的緩衝區中獲得所有的單詞,並閱讀下一個50.

+0

我認爲可以。但是這個操作可能會很慢。因爲在讀取每個單詞時總是必須更新緩衝區數組。 – jacop41 2012-04-11 07:41:44