如何使用对象反序列化Map

时间:2014-04-29 17:57:46

标签: java serialization

我尝试序列化地图。这是我的功能:

Map<Integer,Word> currentMap=new LinkedHashMap<Integer,Word>();

protected void serializeCM(){
    try{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(bos);
        os.writeObject(currentMap);
        String SO = bos.toString();
        os.flush();
        os.close();
        writeFile("serialized.txt",SO,false);
    }
    catch(Exception e){e.printStackTrace();}
}

在我尝试反序列化currentMap

之后
protected Map<Integer,Word> deserializeCM(String f){
    Map<Integer,Word> map=new LinkedHashMap<Integer,Word>();
    String path=System.getProperty("user.dir")+"\\";
    try{
        String str=new String(Files.readAllBytes(Paths.get(path+f)));
        ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
        ObjectInputStream is = new ObjectInputStream(bis);
        map = (LinkedHashMap<Integer,Word>)is.readObject();         
        is.close();
        return map;
    }
    catch(Exception e){e.printStackTrace();};
    return null;
}

这是单词类的外观:

public class Word implements Cloneable, Serializable{

public String l;
public String cap="";
public byte rPos;
public byte time;
public byte a_index;
public byte master = -1;
public Map<Integer,Word> enumerations = new HashMap<Integer,Word>();
public Map<Integer,Boolean> contrs = new HashMap<Integer,Boolean>();

public Object clone(){
    try{return super.clone();}
    catch(Exception e){e.printStackTrace();return this;}
}

}

当我尝试反序列化它时,我得到了这个错误

java.io.StreamCorruptedException: invalid stream header: EFBFBDEF
我在做错了什么?

任何有用的帮助!

1 个答案:

答案 0 :(得分:2)

直接写入文件而不使用 ByteArrayInputStream / ByteArrayOutputStream

序列化:

protected void serializeCM() {
    try {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("serialized.txt"));
        os.writeObject(currentMap);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

反序列化:

protected Map<Integer, Word> deserializeCM(String f) {
    String path = System.getProperty("user.dir") + "\\" + f;

    try {
        Map<Integer, String> map = new LinkedHashMap<Integer, Word>();
        ObjectInputStream is = new ObjectInputStream(new FileInputStream(path));
        map = (LinkedHashMap<Integer, Word>) is.readObject();
        is.close();

        return map;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}