Skip to content
Advertisement

Serialization process constantly overwrites itself?

I’m fairly new to java and trying to do some serialization in my project. I have a bunch of objects called Student and I would like to serialize them. The code I’m using for this is as follows:

JavaScript

The issue I’m finding is that the students array I’m using has twenty students (S1 – S20). When I attempt to deserialize the objects, it only gives me the object that contains the last student to have been serialized (S20)

This is my deserialization code:

JavaScript

I have also noticed that when I open the .ser file, that there is only one line in it. I’m assuming this may be evidence that it is in fact overwriting itself every time as my understanding is that there should be as many lines as there objects in the serialization file.

Can anyone help me to understand what I am doing that is causing the file to overwrite itself instead of retaining objects that have already been added?

Also, here is my Student class for reference:

JavaScript

Advertisement

Answer

JavaScript

You’re creating a new FileOutputStream inside the for-loop, overwriting the old information with each iteration. Don’t do this, create the stream before the loop and use it within the loop:

JavaScript

And close it after the loop.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement