【发布时间】:2013-04-15 06:29:46
【问题描述】:
亲爱的同事,你好,
我有一个 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数组正确构造? -
另外,您需要将 IO 关闭调用放在
finally块中。而且,您不需要ArrayList<Plant> dp = new ArrayList<Plant>();。只需ArrayList<Plant> dp = garden.desearilizePlant();,因为您的数组是在#deserializePlant中创建的 -
为什么在 object != null 时循环?如果您打算向流中写入空值以发出 EOS 信号,这是多余的,如果您希望读取空值而不写入空值,那您就错了。您应该改为捕获 EOFException。
标签: java serialization deserialization outputstream