Amn*_*nor 0 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 ++;
}
Run Code Online (Sandbox Code Playgroud)
它正在工作,我看到正确的打印,但是当它必须结束时,打印最后一行为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
Run Code Online (Sandbox Code Playgroud)
我尝试过其他方法:
while (line2 != "null" )
while (line2.length()>0)
while (!line2.isEmpty)
Run Code Online (Sandbox Code Playgroud)
什么都没有用,我在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
// ...
}
Run Code Online (Sandbox Code Playgroud)
通常的习惯用法,如果你想使用一个while循环,那就是:
while ((line2 = reader2.readLine()) != null) {
// ...use line2
}
Run Code Online (Sandbox Code Playgroud)
分配给line2然后检查结果的指定值null.(这也使line2 = "";上面的循环变得不必要.)
它是少数几个做作业的地方之一,通常可以看到表达式,因为它是如此惯用.
较长的形式是:
line2 = reader2.readLine()
while (line2 != null) {
// ...use line2
// get the next one
line2 = reader2.readLine();
}
Run Code Online (Sandbox Code Playgroud)
...但是通过复制该行,它引入了修改其中一个而不是另一个的可能性,引入了一个错误.
你应该改变呼叫的顺序 line2 = reader2.readLine();
line2 = reader2.readLine();
while (line2 != null) {
// Your code
line2 = reader2.readLine();
}
Run Code Online (Sandbox Code Playgroud)
让我们使用您自己的代码来获取一个实际示例: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
}
Run Code Online (Sandbox Code Playgroud)