Java Dictionary 如何序列化
时间: 2023-07-18 09:29:45 浏览: 51
Java Dictionary 类本身不支持序列化,但是你可以使用 Java 的序列化机制将其转换为可以序列化和反序列化的对象。下面是一个简单的示例代码:
```java
import java.io.*;
public class DictionarySerializationDemo {
public static void main(String[] args) {
// 创建一个 Dictionary 对象
Dictionary<String, String> dict = new Hashtable<>();
dict.put("apple", "a sweet fruit");
dict.put("banana", "a long yellow fruit");
dict.put("cherry", "a small red fruit");
// 序列化 Dictionary 对象
try {
FileOutputStream fileOut = new FileOutputStream("dictionary.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(dict);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in dictionary.ser");
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化 Dictionary 对象
try {
FileInputStream fileIn = new FileInputStream("dictionary.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Dictionary<String, String> newDict = (Dictionary<String, String>) in.readObject();
in.close();
fileIn.close();
// 打印反序列化后的 Dictionary 对象
System.out.println("Deserialized Dictionary:");
for (String key : newDict.keySet()) {
System.out.println(key + ": " + newDict.get(key));
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
这里我们使用了 Java 的标准序列化机制,将 Dictionary 对象写入文件 `dictionary.ser` 中,并从文件中读取反序列化后的对象。注意,在使用 Java 序列化机制时,被序列化的对象必须实现 `java.io.Serializable` 接口。由于 Dictionary 类已经实现了该接口,因此我们可以直接使用标准的序列化机制来序列化和反序列化它。