Java I/O流如何处理序列化对象?
作者:暮色微凉
时间:2024-04-22
浏览:0
JavaI/O流可对对象进行序列化和反序列化,以便传输或存储,具体步骤如下:使对象实现Serializable接口;使用ObjectOutputStream将对象序列化到输出流中;从输入流中读取字节流;使用ObjectInputStream将字节流反序列化成对象。
Java I/O 流可对对象进行序列化和反序列化,以便传输或存储,具体步骤如下:使对象实现 Serializable 接口;使用 ObjectOutputStream 将对象序列化到输出流中;从输入流中读取字节流;使用 ObjectInputStream 将字节流反序列化成对象。

Java I/O流处理序列化对象
简介
序列化是一个过程,将一个对象转换成一个字节流,以便它可以在网络或存储设备上进行传输或存储。反序列化是相反的过程,从字节流中重建一个对象。在 Java 中,序列化和反序列化是通过 I/O 流完成的。
序列化对象
要序列化一个对象,我们需要:
- 使对象实现
Serializable接口。 - 使用
ObjectOutputStream将对象写入到输出流中。
// 序列化一个对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.ser"));
oos.writeObject(object);
oos.close();反序列化对象
要反序列化一个对象,我们需要:
- 从输入流中读取字节流。
- 使用
ObjectInputStream将字节流反序列化成对象。
// 反序列化一个对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.ser"));
Object object = ois.readObject();
ois.close();实战案例
让我们创建一个 Student 类,使其可序列化并演示序列化和反序列化过程:
import java.io.Serializable;
public class Student implements Serializable {
private int id;
private String name;
// 构造函数和 getter/setter 略...
}
public class Main {
public static void main(String[] args) {
// 创建一个 Student 对象
Student student = new Student(1, "John Doe");
// 序列化该对象
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
oos.writeObject(student);
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化该对象
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {
Student deserializedStudent = (Student) ois.readObject();
System.out.println(deserializedStudent.getId() + " " + deserializedStudent.getName());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}运行此代码将输出:1 John Doe,这表明对象已成功序列化和反序列化。
作者最新文章
Photoshop文字外框怎么设置?给文字加边框的实用方法
2026-09-22 16:12
白描 PDF
2026-09-16 17:44
密码键盘
2026-09-16 17:43
3dmax快捷键失效了怎么办
2026-09-16 13:53
Xiaomi 18 Fold首销数据解读:较上代大折叠增长310%的原因与配置分析
2026-09-08 16:55
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































