使用.bin保存/加载HashMap

时间:2012-10-23 15:20:19

标签: java serialization hashmap objectoutputstream objectinputstream

public Map<String, BarrackData> barrack = new HashMap<String, BarrackData>();
SavingData.save(barrack, "barrack.bin"); // save
barrack = (Map<String, BarrackData>)SavingData.load("barrack.bin"); // load
// BarrackData contains 3 int's and 1 String.

public static void save(Object obj, String path) throws Exception {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
    oos.writeObject(obj);
    oos.flush();
    oos.close();
}

public static Object load(String path) throws Exception {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
    Object result = ois.readObject();
    ois.close();
    return result;
}

如何保存/加载HashMap 我使用这种方法,但似乎有问题 barrack.bin包含一些我无法弄清楚的错误 (java.io.NotSerializableException java.io.ObjectStreamException IOException suppressExceptionst)

1 个答案:

答案 0 :(得分:1)

您的班级BarrackData似乎没有实施java.io.Serializable。它应该是这样的:

public class BarrackData implements Serializable {
   ...