Java I/O流如何处理序列化对象?
作者:暮色微凉
时间:2025-05-08
浏览:7
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,这表明对象已成功序列化和反序列化。
作者最新文章
AO3防走失官网链接2025手机版入口
2026-11-22 16:21
抖音搜索app是做什么的 抖音搜索app收费吗
2026-11-19 15:26
腾讯会议本地录制和云录制怎么选 保存路径设置
2026-11-18 17:23
AO3镜像彩云站访问入口及使用指南
2026-11-18 14:16
AO3中文入口及官方镜像链接
2026-11-18 09:24
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































