0

我需要逐行读取文本文件,直到找到特定的字符串。我正在使用BufferedReader.readLine(),但是当我调试时,我发现它从文件的第三行开始,然后跳过行。这是我的代码:

try {
    reader = new BufferedReader(new FileReader(path));

    String line1 = null;

    while ((line1 = reader.readLine()) != null) {
        if (line1.toString() == invocation0) {
            found = true;
            return false;
        } else if (line1 == invocation1) {
            found = true;
            return true;
        }
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (reader != null)
        try {
            reader.close();
        } catch (IOException e) {
        }
}

我真的很感激任何帮助,因为我为此尝试了许多不同的解决方案,但仍然无法解决这个问题。

文件的内容是这样的:

.//================================================ ============================= .// 文件:abc.mark .// 描述:anything .// 注意:anything . // .//============================================== ================================ .invoke RemoveClass("Properties",0)

4

2 回答 2

3
if(line1.equals(invocation0))

使用equals()方法进行String价值比较。

此外,您可以return使用. 这只是一个建议。ifbreak

于 2013-03-27T09:49:00.823 回答
0

BufferedReader 不应该跳过任何内容。不幸的是,您是使用 read 方法跳过该行的人。相等运算符==不会比较任何两个字符串的内容,而是比较它们是否属于同一对象。您可以通过两种方式避免它。

  1. 在 invocation0 上调用 intern() (无论如何,line1 对象应该已经被实习过)
  2. 更准确地使用 equals 方法 line1.equals(invocaton0)

链接可能对您更好地理解它有所帮助。

于 2013-03-27T10:16:29.870 回答