我需要逐行读取文本文件,直到找到特定的字符串。我正在使用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 .//描述:什么都有 .//注意:什么 .// .//========================================== ================================ .invoke RemoveClass(“Properties”,0)
答案 0 :(得分:3)
if(line1.equals(invocation0))
使用equals()
方法进行String
值比较。
此外,您可以使用return
代替if
中的break
。这只是一个建议。
答案 1 :(得分:0)
BufferedReader不应该跳过任何东西。不幸的是,你是那个使用read方法跳过这一行的人。 equlaity运算符==
不会比较任何两个字符串的内容,而是比较它们是否属于同一个对象。您可以通过两种方式避免它。
此link可能对您有所帮助,让您更好地理解它。