我正在编写一个从文件读取的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/