Java 中 ObjectInputStream 和 ObjectOutputStream 的用法128


在 Java 中,ObjectInputStream 和 ObjectOutputStream 类允许你对对象进行序列化和反序列化,将它们存储在文件或网络流中,然后在以后重新创建。

序列化

要序列化一个对象,可以使用 ObjectOutputStream。它将对象及其状态写入一个流,以便稍后可以读取和重建该对象。
import ;
import ;
public class SerializationDemo {
public static void main(String[] args) {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(""))) {
Employee employee = new Employee(1, "John Doe", "@");
(employee);
} catch (IOException e) {
();
}
}
}

反序列化

要反序列化一个对象,可以使用 ObjectInputStream。它从流中读取对象的数据并重建该对象。
import ;
import ;
public class DeserializationDemo {
public static void main(String[] args) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(""))) {
Employee employee = (Employee) ();
("反序列化的对象:" + employee);
} catch (IOException | ClassNotFoundException e) {
();
}
}
}

注意事项

在使用 ObjectInputStream 和 ObjectOutputStream 时需要注意以下几点:* 序列化类必须实现 Serializable 接口。
* 序列化类中的所有成员变量都必须是可序列化的。
* 静态变量和瞬态变量不会被序列化。
* 序列化和反序列化必须使用相同的类和版本。

示例

以下是一个示例,演示如何使用 ObjectInputStream 和 ObjectOutputStream 序列化和反序列化一个 Employee 对象:
public class Employee implements Serializable {
private int id;
private String name;
private String email;
public Employee(int id, String name, String email) {
= id;
= name;
= email;
}
// 其他方法...
}

序列化:
import ;
import ;
public class SerializationDemo {
public static void main(String[] args) {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(""))) {
Employee employee = new Employee(1, "John Doe", "@");
(employee);
} catch (IOException e) {
();
}
}
}

反序列化:
import ;
import ;
public class DeserializationDemo {
public static void main(String[] args) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(""))) {
Employee employee = (Employee) ();
("反序列化的对象:" + employee);
} catch (IOException | ClassNotFoundException e) {
();
}
}
}

2024-11-03


上一篇:Java 中的静态方法调用

下一篇:Java 中调用 main 方法:综合指南