亲爱的同事们,你好:
我有一个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();
编辑
我遇到了空指针异常
@NilsH的解决方案很好用,谢谢!
plants
数组被正确构建了? - wmorrison365ArrayList<Plant> dp = new ArrayList<Plant>();
。只需将ArrayList<Plant> dp = garden.desearilizePlant();
作为数组创建在#deserializePlant
中即可。 - wmorrison365