(line != null) 在 Java BufferedReader 中不工作

(line != null) not working in Java BufferedReader

我正在编写一个从文件中读取的 java 程序,我需要它在文件末尾停止,我记得过去使用 "While(line != null)" 来获取文件中的每一行但是,文本现在对我不起作用。我的方法是这样的:

int contator = 0;
String line2 = "";
while (line2 != null) {
            line2 = reader2.readLine();
            fi[contator]=line2;
            for(int i =0;i<ret.length;i++){
                System.out.println("line2 : "+line2+"ret : "+ret[i]);
                if(line2.toLowerCase().contains(ret[i])){
                    fi[contator] = line2;
                    etiqueta[contator]=etiqueta[contator]+" reti";
                }   
            }contator ++;
         }

它正在工作,我看到正确的打印,但是当它必须结束时,打印最后一行为 null,并以 "java.lang.NullPointerException" 退出;打印

line2 : Number of words ret : 361.
line2 : Something here ret : 369.
line2 : other things ret : 379.23
line2 : nullret : 250.5//this is the problem, after this it throws exception

我尝试了其他方法,例如:

while (line2 != "null" )
while (line2.length()>0)
while (!line2.isEmpty)

没有任何效果,我正在使用 Eclipse IDE Mars.2;任何的想法? 提前致谢。

你应该改变调用顺序line2 = reader2.readLine();

line2 = reader2.readLine();
while (line2 != null) {
    // Your code
    line2 = reader2.readLine();
}

让我们使用您自己的代码举一个实际示例:line2 包含流的最后一行。

while (line2 != null) {              // line2 is not null right now but contains the value of the last line
    line2 = reader2.readLine();      // Since the last line has been read already, this returns null
    // Your code is used with null and thus throws the exception
}

您正在比较 line2 和 null。

您正在为第 2 行分配一个新值。

您正在使用第 2 行做某事。

嗯,这可能是什么问题?

while 在循环开始时循环检查。通过在检查之后放置 line2 = reader2.readLine();,您引入了 line2 现在 成为 null 的可能性,因为 reader2.readLine() 返回 null:

while (line2 != null) {         // <=== Not null here
    line2 = reader2.readLine(); // <=== But now it is, because
                                //      readLine returned null
    // ...
}

如果你想为此使用 while 循环,通常的习惯用法是:

while ((line2 = reader2.readLine()) != null) {
    // ...use line2
}

分配给 line2,然后根据 null 检查分配的结果值。 (这也使得循环上方的 line2 = ""; 变得不必要。)

它是为数不多的地方之一,因为它非常地道,所以执行赋值和检查表达式很常见。

较长的形式是:

line2 = reader2.readLine()
while (line2 != null) {
    // ...use line2

    // get the next one
    line2 = reader2.readLine();
}

...但是通过复制该行,它引入了一种可能性,即您将修改其中一个而不是另一个,从而引入错误。

即使 line2 为 null,while 循环的主体仍将 运行。 (你实际上是在使用 line2 的先前值作为终止条件,这当然是不正确的。)因此将抛出 NPE。

为什么不把赋值放在 while 条件中?

while ((line2 = reader2.readLine()) != null)

在循环测试中赋值并不符合每个人的口味(有些人觉得它令人困惑)但有时它很有用,这种情况就是其中之一。

您已将 "" 分配给 line2,然后将其与 null 进行比较。 可能的解决方案是

while ((thisLine = br.readLine()) != null) {
    System.out.println(thisLine);
}