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對象。