我的问题是,我真的不知道为什么对象没有保存在我的类的字段中,我正在为Semestral项目做一些小型的星形管理程序,用于Java编程。所以我的问题是,为什么当对象正确反序列化但不保存在字段中时。目标文件中的字段是否可能为空?
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 :/你能以某种方式帮助我吗?
发布于 2019-12-10 18:26:48
您应该在写入对象后调用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://stackoverflow.com/questions/59264943
复制相似问题