在Java中,Vector類實(shí)現(xiàn)了Serializable接口,因此可以簡(jiǎn)單地使用Java的序列化機(jī)制對(duì)Vector對(duì)象進(jìn)行序列化。
要序列化一個(gè)Vector對(duì)象,只需將其寫入一個(gè)輸出流,然后稍后從輸入流中讀取。示例代碼如下:
import java.io.*;
import java.util.Vector;
public class SerializeVector {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Element 1");
vector.add("Element 2");
vector.add("Element 3");
try {
// Serialize the Vector
FileOutputStream fileOut = new FileOutputStream("vector.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(vector);
out.close();
fileOut.close();
System.out.println("Vector object has been serialized");
// Deserialize the Vector
FileInputStream fileIn = new FileInputStream("vector.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Vector<String> deserializedVector = (Vector<String>) in.readObject();
in.close();
fileIn.close();
// Print the deserialized Vector
for (String element : deserializedVector) {
System.out.println(element);
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我們首先創(chuàng)建了一個(gè)Vector對(duì)象并添加了一些元素。然后我們將Vector對(duì)象序列化到文件"vector.ser"中,接著我們從文件中反序列化出Vector對(duì)象,并打印出元素。
需要注意的是,當(dāng)序列化Vector對(duì)象時(shí),Vector類及其元素也必須實(shí)現(xiàn)Serializable接口,否則會(huì)拋出NotSerializableException異常。