繁体   English   中英

为什么这段代码会产生NullPointerException?

[英]Why is this code producing 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);

如果您要从BufferedReader中获取文本,则最好阅读教程并看一下示例,因为这种方法可以指示Stream何时完成,是否吐出一个空值,并且您的代码最好已准备就绪为了这种可能。 例如,

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

查看BufferedReader readLine()方法参考:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM