在Java中,HashMap類實現了Serializable接口,因此可以直接進行序列化。以下是一個簡單的示例,展示了如何對HashMap進行序列化和反序列化:
import java.io.*;
import java.util.HashMap;
public class HashMapSerializationExample {
public static void main(String[] args) {
// 創建一個HashMap
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");
hashMap.put("key3", "value3");
// 序列化HashMap
try {
FileOutputStream fileOut = new FileOutputStream("hashMap.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(hashMap);
out.close();
fileOut.close();
System.out.printf("HashMap已序列化到hashMap.ser文件%n");
} catch (IOException i) {
i.printStackTrace();
}
// 反序列化HashMap
HashMap<String, String> deserializedHashMap = null;
try {
FileInputStream fileIn = new FileInputStream("hashMap.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
deserializedHashMap = (HashMap<String, String>) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("HashMap類未找到");
c.printStackTrace();
return;
}
// 輸出反序列化后的HashMap
System.out.println("反序列化后的HashMap:");
for (String key : deserializedHashMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + deserializedHashMap.get(key));
}
}
}
在這個示例中,我們首先創建了一個HashMap,然后將其序列化到名為hashMap.ser
的文件中。接下來,我們從該文件中反序列化HashMap,并將其內容輸出到控制臺。
注意:序列化和反序列化過程中可能會拋出IOException和ClassNotFoundException異常,因此需要進行異常處理。