java序列化和反序列化
时间: 2023-10-30 14:29:29 浏览: 56
Java序列化和反序列化是将对象转换为字节流的过程,以便在网络上传输或将对象保存到磁盘中。它的实现依赖于Serializable接口,该接口标记了一个类可以被序列化。以下是Java序列化和反序列化的基本步骤:
1. 创建一个实现Serializable接口的Java对象。
2. 创建一个ObjectOutputStream对象,该对象可以将Java对象写入输出流中。
3. 使用writeObject()方法将对象写入输出流中。
4. 创建一个ObjectInputStream对象,该对象可以从输入流中读取Java对象。
5. 使用readObject()方法从输入流中读取Java对象。
6. 对象读取后,关闭输入流和输出流。
示例代码:
// 序列化对象
try {
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(employee);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser file");
} catch (IOException i) {
i.printStackTrace();
}
// 反序列化对象
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee e = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Employee object: " + e);
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}