2013-04-12 200 views
1

我賦值和部分寫入一個小程序,它涉及到使用的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。

我也試圖改變如何文件本身的結構,取代了|| (分隔符)用一個詞甚至是空格,但沒有任何變化。

+0

難道你只是讀取文件包含這些字符串,或者它含有你寫實際的疾病的對象? – Kylar

+0

正在讀取的文件只包含這些字符串,我想將其作爲對象編寫。 –

+0

這就是你的問題。您正在嘗試讀取對象,但該文件包含字符串。 – Kylar

回答

3

你的FileInputStream是拋出一個異常(我猜不正確的文件權限,但你必須進一步研究);發生這種情況時,你初始化ObjectInputStream之前,所以ois仍然是空當你達到這導致空指針異常的finally塊。出於這個原因,通過空指針檢查在最終塊中的close語句之前通常是一個好主意。

+0

+1,但我認爲這是一個更好的主意不,直到你知道資源是不可空進入try塊。 –

1

當使用ObjectInputStream時,輸入數據必須是可以讀入序列化對象的字節格式,在本例中爲Disease。如果格式不符合預期格式,將會拋出StreamCorruptedException。如果您手動更改文本文件,有機會,這個異常被拋出,但因爲你是從文件消息讀取顯示通用問題是不顯示的確切消息。

顯示堆棧跟蹤將有助於

iox.printStackTrace(); 

確保您正確輸入所需的對象文件。另外,您可以使用基於文本文件,並使用Printwriter寫,Scanner閱讀。您可以使用||對於作爲Scanner分隔符。