首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从目标文件到字段的反序列化问题

从目标文件到字段的反序列化问题
EN

Stack Overflow用户
提问于 2019-12-10 18:19:07
回答 1查看 36关注 0票数 1

我的问题是,我真的不知道为什么对象没有保存在我的类的字段中,我正在为Semestral项目做一些小型的星形管理程序,用于Java编程。所以我的问题是,为什么当对象正确反序列化但不保存在字段中时。目标文件中的字段是否可能为空?

代码语言:javascript
复制
private void setConstellation(Constellation constellation) {
        Object obj;
        File constellationFile = new File("src\\Constellations\\" + constellation.getNazwa() + ".obj");
        boolean constellationExist = constellationFile.exists();

        if(constellationExist == true) {
            try {
                ObjectInputStream loadStream = new ObjectInputStream(new FileInputStream("src\\Constellations\\" + constellation.getNazwa() + ".obj"));
                while ((obj = loadStream.readObject()) != null) {
                    if (obj instanceof Constellation && ((Constellation) obj).getNazwa().equals(constellation.getNazwa())) {
                        this.constellation = constellation;
                    }
                }
            } catch (EOFException ex) {
                System.out.println("End of file");
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        else if(constellationExist == false){
            try{
                ObjectOutputStream saveStream = new ObjectOutputStream(new FileOutputStream("src\\Constellations\\" + constellation.getNazwa() + ".obj"));
                saveStream.writeObject(constellation);
                this.constellation = constellation;
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
    }

在调试这部分程序时,While循环第一个if‘t event check :/你能以某种方式帮助我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-10 18:26:48

您应该在写入对象后调用saveStream.close(),以确保正确刷新流。

您还应该关闭loadStream

如果您使用的是Java 7或更高版本,则可以使用try-with-resources:

代码语言:javascript
复制
try (ObjectOutputStream saveStream = new ObjectOutputStream(
        new FileOutputStream("src\\Constellations\\" + 
                             constellation.getNazwa() + ".obj"))) {
    saveStream.writeObject(constellation);
    this.constellation = constellation;
} catch (IOException e){
    e.printStackTrace();
}

此构造确保在退出try块时关闭流。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59264943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档