[英]how to serialize/deserialize arrayList(Object)
我有一个ArrayList<ItemList>
其中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();
}
我认为这是有效的,因为我在文件夹中找到了这个文件。
但我无法从文件反序列化到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。
您的Item
和ItemList
类需要implements Serializable
如果您已创建子类,然后将serializabe方法添加到父类,它将删除该错误。
我假设你序列化了ItemList而不是Item .....
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.