反序列化多个Java对象

ima*_*088 8 java serialization outputstream deserialization

亲爱的同事们,

我有一个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) {
    }
}
Run Code Online (Sandbox Code Playgroud)

反序列化代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我的调用代码:

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();
Run Code Online (Sandbox Code Playgroud)

编辑
我得到一个空指针异常
@NilsH的解决方案工作正常,谢谢!

Nil*_*lsH 18

如何序列化整个列表呢?无需序列化列表中的每个单独对象.

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;
}
Run Code Online (Sandbox Code Playgroud)

如果这不能解决您的问题,请发布有关您的错误的更多详细信息.