java中hashmap的反序列化
我正在序列化Java代码中的哈希映射并将其写入文件。反序列化时,文件包含多个值,但它只返回最顶层的键和值对。谁能告诉我为什么?以下是我的反序列化Java代码:java中hashmap的反序列化,java,serialization,hashmap,Java,Serialization,Hashmap,我正在序列化Java代码中的哈希映射并将其写入文件。反序列化时,文件包含多个值,但它只返回最顶层的键和值对。谁能告诉我为什么?以下是我的反序列化Java代码: public static void main(String[] args) throws IOException, ClassNotFoundException { HashMap<String, String> data = new HashMap<Integer, String>(); Ob
public static void main(String[] args) throws IOException, ClassNotFoundException {
HashMap<String, String> data = new HashMap<Integer, String>();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("F:\\f.txt"));
data = (HashMap<String, String>) in.readObject();
for (Map.Entry entry : data.entrySet()) {
System.out.println("key" + entry.getKey());
System.out.println("value" + entry.getValue());
}
}
publicstaticvoidmain(字符串[]args)抛出IOException、ClassNotFoundException{
HashMap数据=新的HashMap();
ObjectInputStream in=新ObjectInputStream(新文件InputStream(“F:\\F.txt”);
data=(HashMap)在.readObject()中;
for(Map.Entry:data.entrySet()){
System.out.println(“key”+entry.getKey());
System.out.println(“value”+entry.getValue());
}
}
这是我的序列化代码
public class SerializeObject implements Serializable {
public static void main(String[] args) throws IOException, ClassNotFoundException
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("Monday","first");
map.put("Tuesday","Second");
map.put("Wednesday","Third");
FileOutputStream fout=new FileOutputStream("F:\\f.txt",true);
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(map);
out.flush();
}
}
public类serialized对象实现可序列化{
公共静态void main(字符串[]args)引发IOException,ClassNotFoundException
{
HashMap=newHashMap();
地图放置(“星期一”、“第一”);
地图放置(“星期二”、“第二”);
地图放置(“星期三”、“第三”);
FileOutputStream fout=新的FileOutputStream(“F:\\F.txt”,true);
ObjectOutputStream out=新的ObjectOutputStream(fout);
out.writeObject(映射);
out.flush();
}
}
在反序列化之后,它只返回星期一和第一次,您应该关闭您的流
out.flush()
可能不足以确保将所有剩余数据写入磁盘。确保这一点的简单方法是使用try with resource
语句:
public static void main(String[] args) throws IOException, ClassNotFoundException
{
HashMap<String,String> map = new HashMap<String,String>();
map.put("Monday","first");
map.put("Tuesday","Second");
map.put("Wednesday","Third");
try (
FileOutputStream fout=new FileOutputStream("F:\\f.txt",true);
ObjectOutputStream out=new ObjectOutputStream(fout); )
{
out.writeObject(map);
}
}
publicstaticvoidmain(字符串[]args)抛出IOException、ClassNotFoundException
{
HashMap=newHashMap();
地图放置(“星期一”、“第一”);
地图放置(“星期二”、“第二”);
地图放置(“星期三”、“第三”);
试一试(
FileOutputStream fout=新的FileOutputStream(“F:\\F.txt”,true);
ObjectOutputStream out=新的ObjectOutputStream(fout);)
{
out.writeObject(映射);
}
}
您使用什么代码来序列化它?f.txt的内容是什么?请修复您的格式。在序列化工作正常后执行反序列化。。。地图的键也从字符串切换到整数?!嗨…对不起,这只是我的错