Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reading serialized in objects from file into an arrayList

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();
}
like image 931
user2380220 Avatar asked Apr 15 '26 03:04

user2380220


2 Answers

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.

like image 97
Evgeniy Dorofeev Avatar answered Apr 17 '26 16:04

Evgeniy Dorofeev


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.

like image 40
Bohemian Avatar answered Apr 17 '26 16:04

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!