java - 我如何用对象反序列化 Map

标签 java serialization

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

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

我做错了什么?

任何帮助appriced!

最佳答案

直接写入文件,而不使用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;
}

关于java - 我如何用对象反序列化 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371941/

相关文章:

xml - 如何将快捷方式命名空间添加到我的 xml 文档中

kotlin - 为什么数据类不能实现Serializable?

java - 自定义字符串长度比较器 : what's my mistake?

java - 为什么消费者线程只有在生产者写完10个对象后才执行

java - 在游戏中正确实现延迟

java - Jodd:不要序列化空对象

php - 将 4 字节大整数写为无符号二进制

java - 安装客户端库 - Google Cloud Text To Speech Java

java - 我发现我的代码在 "socket socket = serverSocket.accept();"之后没有跟随,程序卡在这里

php - 存储序列化数组时进行清理