java - 搜索方法只搜索第一行java

标签 java bufferedreader stringtokenizer

看来我的搜索方法只搜索第一行,没有搜索其他内容。不知道为什么。它应该逐行读取匹配项,如果没有找到,则继续移动到下一行,直到所有行都用完,但是当我使用具有多行的文件测试它并在第 5 行搜索字符串时它返回:在文件中找不到搜索参数。

String Search(String key) throws IOException {

int lines = 0;
String line = "";
String nextLine = "";
String foundAt = "";
BufferedReader BR = new BufferedReader(new FileReader(f));

try  {
   while ((nextLine = BR.readLine()) != null) {
      line = nextLine.toLowerCase();
      lines++;
      StringTokenizer words = new StringTokenizer(line); //create tokenizer words with what is in line
      while(words.hasMoreTokens()) { //while words has tokens left
         if (words.nextToken().equals(key.toLowerCase())) //go to next token and compare to key
            foundAt = foundAt + "\n" + lines + ": " + line;

            //do nothing continue loop                     
         }
      }
      BR.close();
   }  catch(FileNotFoundException e)  {
   }
   if (foundAt == "")
   foundAt = "Search parameter NOT found in file.";
   return foundAt;
}

最佳答案

我发现代码绝对没有问题,我使用以下测试文件进行了尝试:

word line
number two
alice and bob
bar bazz
loop for each
buzz bizz bar bozz
this is some text
lorem ipsum bar
buzz isobar

并搜索“bar”:

System.out.println(Search("bar"));

我得到了以下(预期)结果:

4: bar bazz
6: buzz bizz bar bozz
8: lorem ipsum bar

因此,它可以正确识别包含该单词的行(它甚至跳过包含“bar”作为另一个单词的一部分的最后一行)。

我最好的猜测是您传递了错误的文件路径,因此您有一个 FileNotFoundException,但是当您忽略它时,您没有堆栈跟踪,也没有任何帮助您的信息。尝试在 catch 子句中打印异常,然后重新运行程序:

catch(FileNotFoundException e)
{
    e.printStackTrace();
}

我的第二个最佳猜测是您的测试用例很糟糕(例如您正在搜索的字符串是另一个单词的一部分,或者您在该单词后面有一些标点符号)。尝试运行我的测试用例,看看它是否有效。

关于java - 搜索方法只搜索第一行java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22136120/

相关文章:

java - StringTokenizer 不使用新行创建标记

java - 为什么我会收到 NumberFormatException?

java - 将信息从 Android 应用程序发送到 Web 服务并返回

Java GUI 不会显示

java - BufferedReader 在到达空行时停止读取

java - Java/Scala 中 readline 的奇怪行为

java - 如何使用 HttpURLConnection 传递变量

java - 如何仅从unix时间戳获取月份和年份

java - 将 CSV 文件解析为 HashMap 存储空值

Java - 将 StringTokenizer 保存到数组中以便在其他方法中进一步处理