【问题标题】:Serializing objects with hashMap使用 hashMap 序列化对象
【发布时间】: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


【解决方案1】:

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

更新: 2013-12-31

我并不是想把事情复杂化,但我真的觉得不误导别人是我的责任,所以我再次尝试修复代码。目前HashMap不能追加,请改进它。谢谢!

此代码从您的代码中重构:

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<>();
}

【讨论】:

  • 谢谢!你太棒了。
猜你喜欢
  • 2014-02-10
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
  • 2013-08-02
相关资源
最近更新 更多