你好親愛的同事,反序列化多個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();
編輯
我得到一個空指針異常
@NilsH的解決方案工作正常,謝謝!
你說的「它不工作」是什麼意思?代碼是否編譯?你在運行時遇到錯誤嗎?你準確得到什麼錯誤? – Jesper 2013-04-22 11:12:57
嗨,你看到什麼確切的問題?你是什麼意思,它「不工作,如果要分配給(主)靜態方法調用變量」?在調試器中,您是否看到正確構建的「植物」數組? – wmorrison365 2013-04-22 11:15:01
另外,您需要將IO關閉調用放在'finally'塊中。此外,您不需要ArrayList dp = new ArrayList ();'。只需要'ArrayList dp = garden.desearilizePlant();'因爲你的數組是在'#deserializePlant'中創建的 –
wmorrison365
2013-04-22 11:16:24