Java中的Hashtable实现了Serializable接口,因此可以进行序列化和反序列化操作
import java.io.*;
import java.util.Hashtable;
public class SerializeHashtable {
public static void main(String[] args) {
Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put("key1", "value1");
hashtable.put("key2", "value2");
hashtable.put("key3", "value3");
try {
FileOutputStream fos = new FileOutputStream("hashtable.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(hashtable);
oos.close();
fos.close();
System.out.println("Hashtable serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.Hashtable;
public class DeserializeHashtable {
public static void main(String[] args) {
Hashtable<String, String> hashtable = null;
try {
FileInputStream fis = new FileInputStream("hashtable.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
hashtable = (Hashtable<String, String>) ois.readObject();
ois.close();
fis.close();
System.out.println("Hashtable deserialized successfully.");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
if (hashtable != null) {
System.out.println("Deserialized Hashtable: " + hashtable);
}
}
}
这两个示例分别展示了如何序列化和反序列化Hashtable对象。首先,我们创建一个Hashtable对象并添加一些键值对。然后,我们使用FileOutputStream和ObjectOutputStream将Hashtable对象序列化到文件"hashtable.ser"中。接下来,我们使用FileInputStream和ObjectInputStream从文件中反序列化Hashtable对象。最后,我们打印出反序列化后的Hashtable对象。