我正在为分配编写一个小程序,其中一部分涉及使用 ObjectInputStream 从文件中读取。我遇到了一堵砖墙,因为我在尝试关闭 finally 块中的文件以及 NullPointerException 时不断收到错误,但我不明白为什么。任何帮助深表感谢!我已经检查过了,文件路径是正确的,所以它能够找到文件。
示例文件:你好 || 苹果、巴西莓、香蕉|| 购物|| 0.0005 || 是的
public Disease[] readInCancers() {
Disease[] cancerList = null;
try {
FileInputStream fis = new FileInputStream(myData);
BufferedInputStream bis = new BufferedInputStream(fis);
ois = new ObjectInputStream(bis);
while(true) {
Disease disease = null;
try {
disease = (Disease)ois.readObject();
} catch (EOFException eofx) {
break;
}
if (cancerList == null || cancerList.length == 0) {
cancerList = new Disease[1];
cancerList[0] = disease;
} else {
Disease[] newList = new Disease[cancerList.length + 1];
System.arraycopy(cancerList, 0, newList, 0, cancerList.length);
newList[cancerList.length] = disease;
cancerList = newList;
}
}
} catch (FileNotFoundException fnfx) {
JOptionPane.showMessageDialog(null, "File could not be found");
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem with reading from file");
} catch (ClassNotFoundException cnfx) {
JOptionPane.showMessageDialog(null, "Class could not be found");
} catch (NullPointerException npx) {
System.out.println("blah");
} finally {
try {
ois.close();
} catch (IOException iox) {
JOptionPane.showMessageDialog(null, "Problem with closing file");
}
}
return cancerList;
}
当我运行该程序时,它会在 ois.close() 处提供 NullPointerException 以及产生弹出“从文件读取问题”的 IOException。
我还尝试更改文件本身的结构,替换了 || (分隔符)带有一个单词甚至空格,但没有任何变化。