java序列化和反序列化
时间: 2023-08-03 11:13:46 浏览: 35
Java序列化是将Java对象转换为字节序列的过程,以便将其存储在文件中或通过网络传输。反序列化则是将字节序列转换回Java对象的过程。
下面是一个示例:
```java
import java.io.*;
public class SerializationDemo {
public static void main(String[] args) {
// 创建一个Person对象
Person person = new Person();
person.setName("张三");
person.setAge(20);
try {
// 将Person对象序列化到文件中
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("Person对象已序列化到文件中");
} catch (IOException e) {
e.printStackTrace();
}
try {
// 从文件中读取Person对象并反序列化
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person deserializedPerson = (Person) in.readObject();
in.close();
fileIn.close();
System.out.println("从文件中读取的Person对象:" + deserializedPerson);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
```
运行该程序,输出结果如下:
```
Person对象已序列化到文件中
从文件中读取的Person对象:Person{name='张三', age=20}
```
可以看到,我们将Person对象序列化到了文件中,然后从文件中读取并反序列化回来,最终得到了原始的Person对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)