使用hashMap序列化对象

时间:2013-12-30 14:43:07

标签: java serialization hashmap

这是我第一次尝试对象序列化。 我的问题是,当我调用保存新对象(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;
    }
}

1 个答案:

答案 0 :(得分:1)

我为你做了一个演示和单元测试,目前我使用java.util.Date替换你的SomeDate类。

更新:2013-12-31

我并不是想让事情变得复杂,但我真的觉得不要误导别人是我的责任,所以我试着再次修改代码。目前,HashMap无法追加,请改进它。谢谢!< / p>

此代码从您的代码重构:

import java.io.*;
import java.util.*;

/**
 * refactored by your code
 * append object stream haven't realized,please help 
 * 2013-12-31
 */
public class Reminder implements Serializable {


    public static void main(String[] args) {

        //do some initialization 
        Reminder re = new Reminder();
        re.put(new Date(System.currentTimeMillis()), "Hope it work!");
        re.put(new Date(System.currentTimeMillis()+100), "it work!");
        re.put(new Date(System.currentTimeMillis()+200), "Wake up!");

        //save to file ,using append mode
        String filpath = "/tmp/reminder.ser";
        re.save(filpath,true);

        //load from file and iterate the key-value pair
        Reminder reLoad = Reminder.Load(filpath);
        if(reLoad != null) {
            Iterator<Map.Entry<Date,String>> it = reLoad.entrySet().iterator();
            while(it.hasNext()) {
                Map.Entry<Date,String> entry = it.next();
                System.out.format("reminder: %tc---%s%n",entry.getKey(),entry.getValue());
            }
        }
    }
    public Set<Map.Entry<Date,String>> entrySet() {
        return reminderMap.entrySet();
    }
    public void put(Date chosenDate, String string) {
        reminderMap.put(chosenDate, string);
    }
    public String get(Date chosenDate) {
        return reminderMap.get(chosenDate);
    }
    /**
     * serializing an object
     * @param filePath path to save file
     * @param append  indicate whether append or not
     */
    public void save(String filePath,boolean append){
        System.out.println("Trying to save");
          try
          {
             ObjectOutputStream out = new ObjectOutputStream
             ( new FileOutputStream(filePath,append));
             out.writeObject(this);
             out.close();
             System.out.printf("Serialized data is saved in "+filePath);
          }catch(IOException e)
          {
              e.printStackTrace();
          }
    }
    /**
     * deserialize ,load from file and rebuild object
     * @param filePath the path from where to load
     * @return a new Object
     */
    public static Reminder Load(String filePath) {
        System.out.println("Trying to load");
        Reminder reminder = null;
        try
        {
            ObjectInputStream in = new ObjectInputStream
                 (new FileInputStream(filePath));
            reminder = (Reminder) in.readObject();
            in.close();
        }catch(IOException | ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        return reminder;
    }
   private static final long serialVersionUID = 1L;
   private Map<Date,String> reminderMap = new HashMap<>();
}