gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:52:59 39 4
gpt4 key购买 nike

我尝试序列化 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/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com