反序列化多个Java对象
你好亲爱的同事们,
我有一个Garden类,在其中我可以序列化和反序列化多个Plant类对象。如果想将其分配给mein静态方法中的调用变量,则可以进行序列化,但是不能进行反序列化。
public void searilizePlant(ArrayList<Plant> _plants) { try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (int i = 0; i < _plants.size(); i++) {
out.writeObject(_plants.get(i));
}
out.close();
fileOut.close();
} catch (IOException ex) {
}
}
反序列化代码:
public ArrayList<Plant> desearilizePlant() { ArrayList<Plant> plants = new ArrayList<Plant>();
Plant _plant = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
Object object = in.readObject();
// _plant = (Plant) object;
// TODO: ITERATE OVER THE WHOLE STREAM
while (object != null) {
plants.add((Plant) object);
object = in.readObject();
}
in.close();
} catch (IOException i) {
return null;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
return null;
}
return plants;
}
我的调用代码:
ArrayList<Plant> plants = new ArrayList<Plant>();plants.add(plant1);
Garden garden = new Garden();
garden.searilizePlant(plants);
// THIS IS THE PROBLEM HERE
ArrayList<Plant> dp = new ArrayList<Plant>();
dp = garden.desearilizePlant();
我有一个空的Pointer异常
@NilsH的解决方案工作正常,谢谢!
回答:
如何序列化整个列表呢?无需序列化列表中的每个对象。
public void searilizePlant(ArrayList<Plant> _plants) { try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(_plants);
out.close();
fileOut.close();
} catch (IOException ex) {
}
}
public List<Plant> deserializePlant() {
List<Plants> plants = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
plants = in.readObject();
in.close();
}
catch(Exception e) {}
return plants;
}
如果那不能解决您的问题,请发布有关您的错误的更多详细信息。
以上是 反序列化多个Java对象 的全部内容, 来源链接: utcz.com/qa/412038.html