【发布时间】:2013-12-30 14:43:07
【问题描述】:
这是我第一次尝试对象序列化。 我的问题是,当我调用保存新对象(Reminder.java 对象)时,它会将它们保存在哈希图中,但是当我加载它时,它会给我最后保存对象的属性。
所以我的问题是:
1.Saving - 我如何将对象“附加”到文件中?
2.Loading - 如何遍历它们并获取正确的对象(使用关键类类型 MyDateClass) .示例将受到欢迎。谢谢。
public void save(MyDateClass chosenDate, String string){
System.out.println("Trying to save");
reminderMap.put(chosenDate, string);
//serializing an object :
this.dateReminder = chosenDate;
this.reminder = string;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/reminder.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reminder.ser. ");
}catch(IOException i)
{
i.printStackTrace();
}
}
public String Load(MyDateClass chosenDate){
System.out.println("Trying to load");
this.reminder = reminderMap.get(chosenDate);
System.out.println(this.reminder);
// deserialize
Reminder e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/reminder.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Reminder) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
}catch(ClassNotFoundException c)
{
c.printStackTrace();
}
return e.reminder;
}
}
【问题讨论】:
-
new FileOutputStream("/tmp/reminder.ser");以 create 模式打开文件。寻找另一个允许你以 append 模式打开的构造函数。
标签: java serialization hashmap