多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 如何在 java 中序列化`HashMap` > 原文: [https://beginnersbook.com/2013/12/how-to-serialize-hashmap-in-java/](https://beginnersbook.com/2013/12/how-to-serialize-hashmap-in-java/) `HashMap`类默认是序列化的,这意味着我们不需要实现`Serializable`接口,以使其符合序列化的条件。在本教程中,我们将学习**如何编写`HashMap`对象及其内容到文件**和**如何从文件中读取`HashMap`对象**。在分享完整代码之前,让我简单介绍一下序列化和反序列化。 序列化:这是一个将`Object`与其属性和内容一起写入文件的过程。它在内部以字节流转换对象。 反序列化:这是一个从文件中读取`Object`及其属性以及`Object`内容的过程。 #### 示例: **`HashMap`的序列化:**在下面的类中,我们将`HashMap`内容存储在`hashmap.ser`序列化文件中。运行以下代码后,它将生成一个`hashmap.ser`文件。此文件将在下一个类中用于反序列化。 ```java package beginnersbook.com; import java.io.*; import java.util.HashMap; public class Details { public static void main(String [] args) { HashMap<Integer, String> hmap = new HashMap<Integer, String>(); //Adding elements to HashMap hmap.put(11, "AB"); hmap.put(2, "CD"); hmap.put(33, "EF"); hmap.put(9, "GH"); hmap.put(3, "IJ"); try { FileOutputStream fos = new FileOutputStream("hashmap.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(hmap); oos.close(); fos.close(); System.out.printf("Serialized HashMap data is saved in hashmap.ser"); }catch(IOException ioe) { ioe.printStackTrace(); } } } ``` 输出: ```java Serialized HashMap data is saved in hashmap.ser ``` **反序列化:**这里我们正在重现`HashMap`对象,它是我们通过运行上面的代码创建的序列化文件的内容。 ```java package beginnersbook.com; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Set; public class Student { public static void main(String [] args) { HashMap<Integer, String> map = null; try { FileInputStream fis = new FileInputStream("hashmap.ser"); ObjectInputStream ois = new ObjectInputStream(fis); map = (HashMap) ois.readObject(); ois.close(); fis.close(); }catch(IOException ioe) { ioe.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println("Class not found"); c.printStackTrace(); return; } System.out.println("Deserialized HashMap.."); // Display content using Iterator Set set = map.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry mentry = (Map.Entry)iterator.next(); System.out.print("key: "+ mentry.getKey() + " & Value: "); System.out.println(mentry.getValue()); } } } ``` 输出: ```java Deserialized HashMap.. key: 9 & Value: GH key: 2 & Value: CD key: 11 & Value: AB key: 33 & Value: EF key: 3 & Value: IJ ``` #### 参考: * [`HashMap`文档](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) * [`Serializable` javadoc](https://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html) * [`ObjectOutputStream` javadoc](https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html) * [`ObjectInputStream`文档](https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html) * [`FileInputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html) * [`FileOutputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html)