java - (line != null) 在 Java BufferedReader 中不起作用

标签 java arrays nullpointerexception 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;任何想法? 提前致谢。

最佳答案

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 = ""; 变得不必要。)

这是极少数进行作业并 checkin 表达式的地方之一,因为它非常惯用。

较长的形式是:

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

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

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

关于java - (line != null) 在 Java BufferedReader 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38144712/

相关文章:

java - JAVA数组不保存值

java - 从 servlet 内获取 Web 应用程序类路径

javascript - 每当在网格中单击一行时调用 array.splice() 是否明智

android - 即使应用程序关闭也存储字符串

java - 解决 Android getActivity() 中的 NullPointerException

java - 当我请求操作时,是什么导致了此 NPE?

java - Java 中的 New Relic @Trace 与 Segment

java - 如何编写 XSD 来验证转义的 xml 数据模式

arrays - Swift 字典到数组来填充 pickerView

c++ - 调整动态字符串数组的大小