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,这表明对象已经成功地序列化和反序列化。
以上是Java I/O流如何处理序列化对象?详情请关注图灵教育其他相关文章!