我賦值和部分寫入一個小程序,它涉及到使用的ObjectInputStream讀取文件。我碰到一堵牆,因爲我一直試圖關閉finally塊中的文件,以及一個NullPointerException異常時收到錯誤信息,但我不明白爲什麼。任何幫助深表感謝!我已經檢查過了,文件路徑是正確的,所以它能夠找到文件。IOException異常和NullPointerException異常從ObjectInputStream的
示例文件: 你好||蘋果,acai漿果,香蕉||購物|| 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。
我也試圖改變如何文件本身的結構,取代了|| (分隔符)用一個詞甚至是空格,但沒有任何變化。
難道你只是讀取文件包含這些字符串,或者它含有你寫實際的疾病的對象? – Kylar
正在讀取的文件只包含這些字符串,我想將其作爲對象編寫。 –
這就是你的問題。您正在嘗試讀取對象,但該文件包含字符串。 – Kylar