2011-10-30 42 views
0

我已經使用serialastion將arrayList保存到二進制文件中。我現在如何從二進制文件中檢索這些數據?如何從Java中的二進制文件反序列化數據的ArrayList?

這是我用過的系列化

public void createSerialisable() throws IOException 
{ 
    FileOutputStream fileOut = new FileOutputStream("theBkup.ser"); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 
    out.writeObject(allDeps); 
    options(); 
} 

的代碼,這個我想使用ArrayList中的反序列化的代碼:

public void readInSerialisable() throws IOException 
{ 
    FileInputStream fileIn = new FileInputStream("theBKup.ser"); 

    ObjectInputStream in = new ObjectInputStream(fileIn); 

    try 
    { 
    ArrayList readob = (ArrayList)oi.readObject(); 
       allDeps = (ArrayList) in.readObject(); 
    } 
    catch (IOException exc) 
    { 
     System.out.println("didnt work"); 
    } 
} 

allDeps在聲明數組列表類構造器。我試圖從文件中保存arrayList到這個類中聲明的arrayList。

+0

什麼是數組列表? –

+0

有部門名稱和地址 – Binyomin

+0

什麼是'oi'? –

回答

1

您的代碼大多是正確的,但有一個錯誤,一對夫婦的事情可能使其更好地工作。我用星號突出顯示了它們(因爲顯然,我不能在'代碼'模式下使它們變成粗體)。

public void createSerialisable() throws IOException 
{ 
    FileOutputStream fileOut = new FileOutputStream("theBkup.ser"); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 
    out.writeObject(allDeps); 
    **out.flush();** // Probably not strictly necessary, but a good idea nonetheless 
    **out.close();** // Probably not strictly necessary, but a good idea nonetheless 
    options(); 
} 

public void readInSerialisable() throws IOException 
{ 
    FileInputStream fileIn = new FileInputStream("theBKup.ser"); 

    ObjectInputStream in = new ObjectInputStream(fileIn); 

    try 
    { 
     **// You only wrote one object, so only try to read one object back.** 
     allDeps = (ArrayList) in.readObject(); 
    } 
    catch (IOException exc) 
    { 
     System.out.println("didnt work"); 
     **exc.printStackTrace();** // Very useful for findout out exactly what went wrong. 
    } 
} 

希望有所幫助。如果您仍然看到問題,那麼請確保您發佈了堆棧跟蹤和一個可以展示問題的完整,自包含的可編譯示例。

請注意,我們假設allDeps包含的對象實際上是Serializable,而您的問題位於readInSerialisable而不是createSerialisable。同樣,堆棧跟蹤將非常有幫助。

+0

非常感謝卡梅隆,但.. 它仍然不能編譯,「其稱未報告的異常ClassNotFound的必須捕獲或聲明拋出」 在線:allDeps1 =(ArrayList的)in.readObject(); – Binyomin

+0

哦。你沒有提到它是一個* compile *錯誤。這很簡單:在try塊後添加一個catch(ClassNotFoundException e)塊。或者只是將catch(IOException exc)更改爲catch(Exception exc)'。 –

+0

感謝您的幫助,現在一切正常:) – Binyomin

相關問題