我有一个名为UploadList的ObjectsList(UploadedItem),我可以在每次更新后自动序列化。但是,我无法在启动时反序列化。以下是与过程分开的类。
UploadModel:
public class UploadModel extends Observable {
ArrayList<UploadItem> UploadedList = new ArrayList<>();
Deserialize _deserialize = new Deserialize();
Serialize _serialize = new Serialize();
private UploadItem name;
public UploadModel ()
{
_deserialize.startup();
}
public void addUpload(String[] ToUpload)
{
UploadItem _UploadItem = new UploadItem();
_UploadItem.ArrayToString(ToUpload);
UploadedList.add(_UploadItem);
setChanged();
notifyObservers(UploadedList);
_serialize.save(UploadedList);
}
}
UploadItem(这是我的arraylist中的内容):
public class UploadItem implements Serializable{
String VideoTitle;
String VideoPath;
String ThumbnailPath;
String VideoDesc;
String VideoTags;
public void ArrayToString(String[] ToUpload){
VideoTitle = ToUpload[0];
VideoPath = ToUpload[1];
ThumbnailPath = ToUpload[2];
VideoDesc = ToUpload[3];
VideoTags = ToUpload[4];
}
}
序列化(据我所知,这在每次更新程序时都会发生。):
public class Serialize{
public void save (ArrayList<UploadItem> UploadedList)
{
try
{
FileOutputStream fos = new FileOutputStream("datafile");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(UploadedList);
oos.close();
}
catch(Exception e){
System.out.print(e);
}
}
}
反序列化(不起作用,在启动时发生):
public class Deserialize {
ArrayList<UploadItem> UploadedList;
public void startup ()
{
try
{
FileInputStream fis = new FileInputStream("datafile");
ObjectInputStream ois = new ObjectInputStream(fis);
UploadedList.add(ois.readObject());
ois.close();
}
catch(IOException e)
{
System.out.print("Problem in readFile" + e);
e.printStackTrace();
}
catch(ClassNotFoundException c)
{
System.out.println("Class not found");
c.printStackTrace();
}
}
}
答案 0 :(得分:1)
您正在序列化ArrayList对象。在反序列化时,你得到相同的对象(正确的转换后)。
更改行
UploadedList.add(ois.readObject());
到
UploadedList = (ArrayList<UploadItem>)ois.readObject();