NullPointerException和BufferedReader [英] NullPointerException and BufferedReader

查看:72
本文介绍了NullPointerException和BufferedReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序不断向我抛出nullPointerException,我不知道为什么.我以为可能是因为有bufferedReader,但我不确定.

my program keeps throwing nullPointerException at me and I have no idea why. I thought maybe it's because of the bufferedReader but I'm not sure.

String line = reader.readLine();
while (!line.isEmpty()) {
    line = repairLine(line);
    tree.add(line);
    line = reader.readLine();
}

是的,它包裹在try-catch块中.它说问题出在网上.它不适用于"if(line!= null)".我真的不知道是什么原因造成的.谢谢您的帮助.

Yes, it is wrapped in try - catch block. It says that the problem is on the while-line. It didn't work with "if (line != null)". I really don't know what could cause that. Thanks you for any help.

推荐答案

问题似乎出在您的代码的以下几行:

The problem seems to be with the following lines of your code :

String line = reader.readLine();
while (!line.isEmpty()) {   

}

如果没有要从文件读取的内容,则该行将为null.因此,while循环中的异常.您正在尝试在空引用上调用方法.

If there is nothing to read from the file, line will be null. Thus the exception in the while loop. You are trying to call a method on a null reference.

话虽这么说,从文件中读取行的传统方法是在while条件本身(未测试代码)中将读取的行分配给变量:

That being said, the traditional way of reading lines from a file is to assign the line read to a variable in the while condition itself (code not tested) :

String line = "";
while ((line=reader.readLine()!=null) && !line.isEmpty()) {
    line = repairLine(line);
    tree.add(line);
}

这篇关于NullPointerException和BufferedReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆