序列化HashMap集合的方法:
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
try {
FileOutputStream fileOut = new FileOutputStream("hashmap.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(map);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
反序列化HashMap集合的方法:
HashMap<String, String> map = null;
try {
FileInputStream fileIn = new FileInputStream("hashmap.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
map = (HashMap<String, String>) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 使用反序列化后的HashMap对象
if (map != null) {
System.out.println("Deserialized HashMap: " + map);
}
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: hashmap的应用场景有哪些