2012-07-09 68 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