有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    如果要从BufferedReader中获取文本,最好阅读教程并查看示例,因为判断流何时完成的方法是,它是否抛出空值,并且您的代码最好为这种情况做好准备。e、 g

    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
    
  2. # 2 楼答案

    查看BufferedReader readLine()方法引用:

    Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

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