java 中序列化与反序列化举例说明
时间: 2023-07-18 12:30:33 浏览: 54
Java中的序列化和反序列化是将对象转换为字节流(序列化)或将字节流转换为对象(反序列化)的过程。这种机制可以将Java对象在网络上传输或者将对象保存到本地文件中。
下面以一个简单的示例来说明Java中的序列化和反序列化的使用:
1. 创建一个Person类,包含姓名和年龄两个属性,并实现Serializable接口,表示该类可以被序列化。
```java
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
2. 序列化对象:将Person对象转换为字节流,并保存到本地文件中。
```java
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Person person = new Person("张三", 20);
try {
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("对象已经被序列化并保存到本地文件。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. 反序列化对象:从本地文件中读取字节流,将其转换为Person对象。
```java
import java.io.*;
public class DeserializeDemo {
public static void main(String[] args) {
Person person = null;
try {
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
person = (Person) in.readObject();
in.close();
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("姓名:" + person.getName());
System.out.println("年龄:" + person.getAge());
}
}
```
通过以上实例,我们可以看到序列化和反序列化的过程,它们可以将Java对象在不同的应用程序或不同的平台之间进行传输和共享。