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);
# 1 楼答案
如果要从BufferedReader中获取文本,最好阅读教程并查看示例,因为判断流何时完成的方法是,它是否抛出空值,并且您的代码最好为这种情况做好准备。e、 g
# 2 楼答案
查看BufferedReader readLine()方法引用:
因此,当到达输入流中的结尾时,此函数返回null,您将尝试在其上调用split()方法