HashMap类默认是序列化的,这意味着我们不需要实现Serializable接口,以使其符合序列化的条件。在本教程中,我们将学习如何编写HashMap对象及其内容到文件和如何从文件中读取HashMap对象。在分享完整代码之前,让我简单介绍一下序列化和反序列化。
序列化:这是一个将Object与其属性和内容一起写入文件的过程。它在内部以字节流转换对象。
反序列化:这是一个从文件中读取Object及其属性以及Object内容的过程。
示例:
HashMap的序列化:在下面的类中,我们将HashMap内容存储在hashmap.ser序列化文件中。运行以下代码后,它将生成一个hashmap.ser文件。此文件将在下一个类中用于反序列化。
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(); } }}
输出:
Serialized HashMap data is saved in hashmap.ser
反序列化:这里我们正在重现HashMap对象,它是我们通过运行上面的代码创建的序列化文件的内容。
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()); } }}输出:
Deserialized HashMap..key: 9 & Value: GHkey: 2 & Value: CDkey: 11 & Value: ABkey: 33 & Value: EFkey: 3 & Value: IJ
