HashMap集合的序列化与反序列化方法

   2024-10-01 7020
核心提示:序列化HashMap集合的方法:将HashMap集合写入到文件中:使用ObjectOutputStream类的writeObject()方法将HashMap对象写入到文件中

序列化HashMap集合的方法:

将HashMap集合写入到文件中:使用ObjectOutputStream类的writeObject()方法将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集合:使用ObjectInputStream类的readObject()方法从文件中读取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);}

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号