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

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

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循环:/ 你能以某种方式帮助我吗?

hunanldxyl 回答:从目标文件到字段反序列化的问题

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

您还应该关闭loadStream

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

try (ObjectOutputStream saveStream = new ObjectOutputStream(
        new FileOutputStream("src\\Constellations\\" + 
                             constellation.getNazwa() + ".obj"))) {
    saveStream.writeObject(constellation);
    this.constellation = constellation;
} catch (IOException e){
    e.printStackTrace();
}

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

本文链接:https://www.f2er.com/2950304.html

大家都在问