2014-05-25 266 views
-1

嘿,我有以下方法,通过查看一个大的.txt文件并检查单词是否存在,检查单词是否是合法的单词。此时该方法只能正常工作,如果.txt文件中的单词在相同的行上,且彼此之间只有一个空格。有什么办法可以让它逐行读出单词列表;如果每行有一个字。例如,如果.txt文件是面向这样的:Java缓冲读取器,逐行阅读

字1

单词2

这里是我的方法:

private boolean isWord(String word){ 
    try{ 
     //search .txt file of valid words. !!Will only read properly if there is a single space between each word. 
     BufferedReader in = new BufferedReader(new FileReader("/Users/user/Documents/workspace/AnagramAlgorithm/src/words.txt")); 
     String str; 
     while ((str = in.readLine()) != null){ 
      if (str.indexOf(word) > -1){ 
       return true; 
      } 
      else{ 
       return false; 
      } 
     } 
     in.close(); 
    } 
    catch (IOException e){ 
    } 
    return false; 
} 

回答

1

在你的代码,如果第一行不包含单词你立即返回false。将其更改为只在完成整个文件时返回false:

while ((str = in.readLine()) != null){ 
    if (str.equals(word)){ 
     return true; 
    } 
} 
return false;