2012-07-09 134 views
14

我有一個ArrayList<ItemList>如何序列化/反序列化的ArrayList(對象)

其中ITEMLIST是:

public class ItemList { 
    public ArrayList<Item> it = new ArrayList<Item>(); 
    public String name = ""; 

    public ItemList() { 
    } 
} 

和項目是:

public class Item { 
    public String name = ""; 
    public int count = 0; 

    public Item() { 
    } 
} 

我嘗試序列這份名單:

try { 
      FileOutputStream fileOut = new FileOutputStream(sdDir + serFile); 
      ObjectOutputStream out = new ObjectOutputStream(fileOut); 
      out.writeObject(List_Of_Lists); 
      out.close(); 
      fileOut.close(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

I thi這是工作,因爲我發現這個文件在文件夾中。

但我無法從文件反序列化到ArrayList<ItemList>

代碼:

 try { 
      FileInputStream fileIn = new FileInputStream(sdDir + serFile); 
      ObjectInputStream in = new ObjectInputStream(fileIn); 
      List_Of_Lists = (ArrayList<ItemList>) in.readObject(); 
      Log.i("palval", "dir.exists()"); 
      in.close(); 
      fileIn.close(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

我怎麼可以反序列化這個ArrayList<ItemList>? 我總是發現IOException。

+0

請發佈整個異常堆棧跟蹤 – Tomer 2012-07-09 15:46:25

+0

您是否僅序列化ArrayList,即「it」變量或類ItemList? – prashant 2012-07-09 15:51:09

+0

'我總是發現IOException'。是的,但你讀過它包含的信息嗎?它包含答案。 – EJP 2012-07-11 23:54:16

回答

13

ItemItemList類需要implements Serializable

+1

thx,現在工作。 – Val 2012-07-09 16:02:47

+0

什麼是項目實現可分配?它可以同時實現序列化嗎? – 2016-01-24 23:39:33

+0

@the_prole我不確定你的意思是「什麼是項目實現可分包?」。關於「它可以同時實現序列化」可能是因爲類可以實現多個接口,而'Serializable'實際上並沒有引入任何新的方法,所以不應該有任何衝突。 – Pshemo 2016-01-24 23:43:57

-1

我假設你已經序列化的ITEMLIST不是項目.....

ArrayList<ItemList> arr = (ArrayList<ItemList>) in.readObject(); 

for (ItemList a : arr) 
    { 
     // In this loop by iterating arr, you will get the whole List of ItemList 

    } 
+0

w8。我會嘗試... – Val 2012-07-09 15:48:58

+0

確定..讓我知道..實際上沒有你的完整代碼,所以很難猜出 – 2012-07-09 15:49:32

+0

Item,ItemList需要實現Serializable。 – Val 2012-07-09 16:03:07

0

如果你已經子類再加入serializabe方法父它會刪除錯誤。

+0

你有代碼示例嗎? – mhatch 2016-12-20 21:37:23