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

标签 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();
    }
    }

每当我使用此方法时,我都会得到想要的输出,但它确实会产生空指针异常,并且编译器指向此行:

 String[] split = currentLine.split(" - ", 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

关于java - 为什么这段代码会产生 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23583965/

相关文章:

java - 将 http 请求中的 keep-alive header 设置为 false

java - 这个(不安全的)代码会使 JVM 崩溃吗?

android - 如何使用 sd 卡中的图像 url 启动图库应用程序

android - Ecclipse Android Sdk 中的 NullPointerException 不幸的是 myapp 已停止

java - Eclipse Mars 工具栏条目有几个缺口

java - servlet 类的 doPost 方法没有给出所需的结果

java - 如何使用 log4j 设置 ebean 日志级别

java - 为什么接口(interface)方法不能是 "static"& "final"?

java - 空指针异常。不想将空行添加到文件列表中

java - 什么是NullPointerException,我该如何解决?