I'm attempting to read a file that contains serialized objects of type Contact into an ArrayList contactsCollection. The issue I'm having is that the objects Contact never get added into the ArrayList.
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("contactList.dat"));
Contact temp;
while (in.available()!=0)
{
temp = (Contact)in.readObject();
contactsCollection.add(temp);
}
in.close();
}
This is a known behaviour of ObjectInputStream.available, it always returns 0, see https://bugs.java.com/bugdatabase/view_bug?bug_id=4954570. Instead, you can read objects from file until EOFException is thrown, catch it and break.
Actually, you entire approach is wrong: You should serialize the List, not each object.
All List implementations are Serializable. Just create the list, add your onjbects and serialize the list - the objects in it will be serialized too (if they implement Serializable, which obviuosly your do).
Then to deserialize, simply read in the object, and voila - you have a list with all our objects added in already.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With