1.如果利用for-each循环,处理不好就会报错
在这里插入图片描述

2.我们直接将对象放入容器然后直接将容器写入文件,最好进行读取。
//写入
ObjectOutputStream oos=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("obj4.ser")));
/*不需要这样写
for (String key:m.keySet()){
oos.writeObject(m.get(key));
oos.flush();
}
oos.close();*/
oos.writeObject(m);
oos.flush();
oos.close();
//读
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("obj4.ser")));
/*这样有误
Human human=null;
while (true) {
if (ois.readObject() != null) {
//这里会报错 at java.base/java.io.ObjectInputStream$BlockDataInputStream.peekByte
human = (Human) ois.readObject();
} else {
break;
}
if (human instanceof Human) {
Human humanObject = (Human) human;
System.out.println(humanObject);
}
}*/
m=(Map<String,Human>)ois.readObject();
ois.close();
for (String key:m.keySet()){
System.out.println(m.get(key));
}
输出结果

1123

被折叠的 条评论
为什么被折叠?



