我遇到了ObjectOutputStream
/ ObjectInputStream
的怪异行为。
我想将Sitzplatz
类型的特定数量的对象写入文件belegung
。到目前为止,一切都很好。但是,如果我尝试再次读取这些对象,它们都只会返回null
这是我的代码:
public void getBelegtePlaetze() {
if (belegung.exists()) {
try {
FileInputStream fis = new FileInputStream(belegung);
ObjectInputStream ois = new ObjectInputStream(fis);
Sitzplatz platz = (Sitzplatz) ois.readObject();
while (platz != null) {
System.out.println(platz.getId());
platz = (Sitzplatz) ois.readObject();
}
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void speichereSitzplatzDaten() {
FileOutputStream fos;
if (!belegung.exists()) {
try {
belegung.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
fos = new FileOutputStream(belegung, true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (int i = 0; i < kundenListe.size(); i++) {
Sitzplatz platz = kundenListe.get(i).getPlatz();
platz.setId(Integer.toString(i));
oos.writeObject(platz);
}
oos.writeObject(null); // Markiert EOF
oos.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
由于我已经在程序中ArrayList kundenListe
工作了很多,所以我可以100%确保正确设置了其中的数据。
在此程序中,我也已经使用过ObjectOuputStream
,并且几乎复制了代码,但是仍然无法正常工作。
你能告诉我我在做什么错吗?
更新: 我已经尝试了评论中的建议,但是仍然遇到相同的问题。 我将代码减少到下面的小部分,应该可以100%工作,因为我已经在另一个类中使用了该代码。不知道为什么它可以在另一个类而不是那个类中起作用。
private File belegung = new File("belegung.kos");
public void getBelegtePlaetze() {
if (belegung.exists()) {
try {
FileInputStream fis = new FileInputStream(belegung);
ObjectInputStream ois = new ObjectInputStream(fis);
Pakett platz = (Pakett) ois.readObject();
System.out.println(platz.getId());
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void speichereSitzplatzDaten() {
FileOutputStream fos;
if (!belegung.exists()) {
try {
belegung.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
try {
fos = new FileOutputStream(belegung);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Pakett platz = new Pakett();
platz.setId("test");
oos.writeObject(platz);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}