我有这个代码:
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/