【发布时间】:2018-06-03 13:46:45
【问题描述】:
我的代码必须通过 ObjectOutputStream 读取两种不同的对象类型(Bestellung、AKunde)并将其保存在一个 csv 文件中,这样才有效。 但是当我尝试从文件中读取它们时它不起作用。 代码如下:
输出流:
LinkedList<Bestellung> bestellListe = verwaltungBestell.getBestellListe();
try {
fileOutputStream = new FileOutputStream(file);
outputStream = new ObjectOutputStream(fileOutputStream);
for (AKunde kunde : kundenliste) {
outputStream.writeObject(kunde);
}
for (Bestellung bestellung : bestellListe) {
outputStream.writeObject(bestellung);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
输入流:
ArrayList<AKunde> kundenImport = new ArrayList<AKunde>();
ArrayList<Bestellung> bestellungenImport = new ArrayList<Bestellung>();
boolean cont = true;
try {
ObjectInputStream objectStream = new ObjectInputStream(new FileInputStream(directorie));
while (cont) {
AKunde kunde = null;
try {
kunde = (AKunde) objectStream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (kunde != null) {
kundenImport.add(kunde);
} else {
cont = false;
}
}
while (cont) {
Bestellung bestellung = null;
try {
bestellung = (Bestellung) objectStream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (bestellung != null) {
bestellungenImport.add(bestellung);
} else {
cont = false;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
}
但它不会读取“Bestellungen”,也不会将它们保存到“bestellungenImport”中。 谁有解决办法???
【问题讨论】:
-
您需要通过提供确切的问题来澄清
-
执行代码时会发生什么?
-
当我执行“AKunden”时,会添加到“kundenImport”,但“Bestellung 对象”不会添加到“bestellungenImport”中
-
@luk2302 在他的回答中解释了原因。
标签: java stream inputstream outputstream fileinputstream