为什么这段代码产生NullPointerException?

时间:2014-05-10 17:04:22

标签: java nullpointerexception

我有这段代码:

 public void queryForId(){
    String itemName = textField.getText().substring(7, textField.getText().length());
    String br = System.getProperty("line.separator") + " ";
    try {

        once = false;
        item_found = false;

        BufferedReader bure = new BufferedReader(new FileReader("itemList.txt"));

        while (true) {


            String currentLine = bure.readLine();
            String[] split = currentLine.split(" - ", 2);

            if (split[1].equalsIgnoreCase(itemName)) {

                String id = split[0].replace("\uFEFF", "");// removes the BOM.
                textArea.append(br + "[Innovate] The ID(s) of the item '" + itemName + "' is : " + id + ".");
                textField.setText("");
                item_found = true;

            } else {

                if (!once && !item_found) {
                    textArea.append(br + "[Innovate] The Item cannot be found.");
                    textField.setText("");
                    once = true;
                }
            }

        }


    } catch(IOException z){

        z.printStackTrace();
    }
    }

每当我使用这个方法时,我得到我想要的输出,但它确实产生了一个nullpointer异常,编译器指向这一行:

 String[] split = currentLine.split(" - ", 2);

2 个答案:

答案 0 :(得分:2)

如果您要从BufferedReader获取文本,那么您最好阅读教程并查看示例,因为告诉Stream何时完成,是否吐出null,并且你的代码最好为这种可能性做好准备。如,

BufferedReader in = ....;
String inputLine = "";

// test for null here when reading in from the Reader
while ((inputLine = in.readLine()) != null) {
    // use inputLine here
}
// close BufferedReader here, usually in a finally block

答案 1 :(得分:2)

查看BufferedReader readLine()方法参考:

  

返回:   包含行内容的String,不包括任何行终止字符;如果已到达流的末尾,则为null

因此,当到达输入流的末尾时,此函数返回null,您正在尝试调用split()方法。