序列化与反序列化实例
时间: 2023-11-11 17:52:04 浏览: 55
序列化(Serialization)是指将对象转换为字节流的过程,以便于存储或传输。反序列化(Deserialization)则是将字节流转换为对象的过程。
以下是一个使用 Java 进行序列化与反序列化的示例:
```java
import java.io.*;
class MyClass implements Serializable {
private static final long serialVersionUID = 1L;
public int num;
public String str;
public MyClass(int num, String str) {
this.num = num;
this.str = str;
}
}
public class SerializationExample {
public static void main(String[] args) {
// 创建对象
MyClass obj = new MyClass(123, "Hello World!");
// 序列化对象
try {
FileOutputStream fileOut = new FileOutputStream("object.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.println("对象已序列化并保存到 object.ser 文件");
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化对象
MyClass newObj = null;
try {
FileInputStream fileIn = new FileInputStream("object.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
newObj = (MyClass) in.readObject();
in.close();
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
return;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
// 输出反序列化后的对象内容
System.out.println("反序列化后的对象内容:");
System.out.println("num: " + newObj.num);
System.out.println("str: " + newObj.str);
}
}
```
在上述示例中,`MyClass` 类实现了 `Serializable` 接口,这个接口没有任何方法,只是一个标记接口,表示该类可以被序列化。
首先,我们创建了一个 `MyClass` 对象并给它赋值。然后,使用 `FileOutputStream` 和 `ObjectOutputStream` 将对象序列化并保存到文件 `object.ser` 中。
接下来,使用 `FileInputStream` 和 `ObjectInputStream` 从文件中读取字节流,并将其反序列化为新的 `MyClass` 对象。
最后,我们输出反序列化后的对象内容,可以看到它与原始对象的内容相同。
需要注意的是,序列化和反序列化的类必须具有相同的 serialVersionUID 值,否则在反序列化时可能会出现 `InvalidClassException` 异常。在示例中,我们手动指定了 serialVersionUID 为 1L。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)