gpt4 book ai didi

java - 如何将不同类型的多个集合序列化/反序列化到单个文件中

转载 作者:行者123 更新时间:2023-12-01 11:34:53 25 4
gpt4 key购买 nike

我对这个主题做了一些研究,但是我自己没有找到任何解决方案。

问题是这样的:我得到了三个不同类型的独立 Set 对象。

示例:

private static Set<Vessel> vessels = new HashSet<Vessel>();
private static Set<Seperator> vessels1 = new HashSet<Seperator>();
private static Set<Pipe> vessels2 = new HashSet<Pipe>();

Vessel、Seperator 和 Pipe 实现 Serialized 接口(interface)。

简化示例:

public class Vessel implements Serializable{
private static final long serialVersionUID = 1L;
int id;
public Vessel(int id){
this.id = id;
}
}

public class Seperator implements Serializable{
private static final long serialVersionUID = 1L;
int id;
public Seperator(int id){
this.id = id;
}
}

public class Pipe implements Serializable{
private static final long serialVersionUID = 1L;

int id;
public Pipe(int id){
this.id = id;
}
}

我确实知道如何将这些集合序列化为单独的文件。然而,我很难找到一种方法将所有三个独立集序列化到一个文件中,这最终是我查询的目标。

理想情况下,我正在寻找有关如何将不同类型的多个集合序列化和反序列化到单个文件中的示例。

最佳答案

@Vasu 建议的方法应该适合您。然而,当您只想反序列化一组时,这会带来反序列化完整链接列表(集合)的额外成本。因此,您的问题的完整解决方案可以在数据库等持久存储中实现,但不能在文件系统中实现。我粘贴了之前有关相关主题的 SO 帖子的以下评论。

Why can't a file that contains multiple appended ObjectOutputStreams be deserialized by one ObjectInputStream?

Using the default implementation of serialization, there must be a one-to-one mapping between ObjectOutputStream construction and ObjectInputStream construction. ObjectOutputStream constructor writes a stream header and ObjectInputStream reads this stream header. A workaround is to subclass ObjectOutputStream and override writeStreamHeader(). The overriding writeStreamHeader() should call the super writeStreamHeader method if it is the first write to the file and it should call ObjectOutputStream.reset() if it is appending to a pre-existing ObjectOutputStream within the file.

关于java - 如何将不同类型的多个集合序列化/反序列化到单个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30105018/

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