Vardens Archangel
Vardens Archangel

Reputation: 375

Deserialization of ArrayList reads only one object

I'd like to know why my program is reading only 1. element of written objects. I have 2 classes:

public class Sheet implements Serializable{

int something1;
String something2;
}

next one:

public class Book implements Serializable{

ArrayList<Sheet> menu = new ArrayList<Sheet>();

public void newSheet(Sheet temp)
{ menu.add(temp);}

}

Saving Book (in class main Book is static Book Libro = new Book();)

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream        ("libro.obiekt"));
                out.writeObject(Libro);
                out.close();

and reading:

    ObjectInputStream in = new ObjectInputStream(new FileInputStream("libro.obiekt"));
        Libro = (Book) in.readObject();
        in.close();

When I do this, while having for example: 5 objects in ArrayList inside Libro, I can read only first one, while other 4 would be NULL objects.... Any idea what am I doing wrong?

Upvotes: 2

Views: 1545

Answers (1)

Dineshkumar
Dineshkumar

Reputation: 4245

You can only read one object from file (serialized).

The reasons:

  • Each time you write object to file. you are overwritting it. so you can only get the last object written.
  • even if you do set append to true

    FileOutputStream fout = new FileOutputStream(new File(file),true);
      //setting the append to true
    

deserializing will cause

java.io.StreamCorruptedException: invalid type code

To overcome it:

1. You could put all your objects in a list and write it as a whole (your arraylist). serialize list of objects as a whole and deserialize it.

2. you can write each object in different file and read from it.

Upvotes: 1

Related Questions