序列化和反序列化对象的ArrayList

时间:2016-02-27 22:03:51

标签: java arrays

我有一个后面在构造函数public ArrayList<Brick> bricks;中定义的对象bricks = new ArrayList<Brick>();的arrayList。然后在paintComponent方法中使用:

public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    super.paintComponent(g);
     for(Brick b: bricks){
        b.draw(g2d, b.type);
     }

    Toolkit.getDefaultToolkit().sync();
}

使用序列化方法添加一堆对象后:

    public void serialize(ArrayList<Brick> al){
        try{
            FileOutputStream fos= new FileOutputStream("levels/level1");
            ObjectOutputStream oos= new ObjectOutputStream(fos);
            oos.writeObject(al);
            oos.close();
            fos.close();
          }catch(IOException ioe){
               ioe.printStackTrace();
          }
    }

将其保存到文件中(虽然Eclipse会抛出一些警告,正在创建文件)。但是我遇到了反序列化问题(列表没有被加载):

public void deserialize(){
    try
    {
        FileInputStream fis = new FileInputStream("levels/level1");
        ObjectInputStream ois = new ObjectInputStream(fis);
        ArrayList<Brick> readObject = (ArrayList<Brick>) ois.readObject();
        bricks = readObject;
        ois.close();
        fis.close();
     }catch(IOException ioe){
         ioe.printStackTrace();
         return;
      }catch(ClassNotFoundException c){
         System.out.println("Class not found");
         c.printStackTrace();
         return;
      }
}

我做错了吗?

0 个答案:

没有答案