2012-04-11 105 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