gpt4 book ai didi

java - 使用序列化读取和写入java对象

转载 作者:行者123 更新时间:2023-12-02 07:24:23 25 4
gpt4 key购买 nike

现在写我有这个类,我希望能够使用序列化保存和打开它:

public class Region implements Serializable
{
private final int inputNumberOfColumnsAlongXAxis;
private final int inputNumberOfColumnsAlongYAxis;
private double inputDataScaleReductionOnXAxis;
private double inputDataScaleReductionOnYAxis;

private int numberOfColumnsAlongXAxis;
private int numberOfColumnsAlongYAxis;
private int cellsPerColumn; // Z-Axis dimension
private float inhibitionRadius;
private final float percentMinimumOverlapScore;
private final float minimumOverlapScore;

我以前从未做过对象序列化,因此我们将不胜感激!

最佳答案

您需要做的最简单的事情就是向您的类添加一个名为 serialVersionUID 的私有(private)静态字段。例如:

private static final long serialVersionUID = 1L;

默认序列化机制使用它来匹配类名和格式。

然后,您可以将对象的实例写入 ObjectOutputStream 并从 ObjectInputStream 读回它们:

Region r = . . .;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(r);
oos.close();
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(bos.getBytes()));
Region r2 = (Region) ois.readObject();
// voilà - a very expensive clone()!

为了更好地控制对象序列化,您可以实现以下方法:

private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;

然后您就可以完全控制对象的序列化。有关更多信息,请参阅 Serializable 上的文档.

更新:严格来说,您不需要声明serialVersionUID;如果缺少,运行时环境会自动为您计算一个。然而,文档对此有这样的说法(强调原文):

However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

关于java - 使用序列化读取和写入java对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13748307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com