Search code examples
javaobjectserializable

Know the amount of objects Serializable from file


I am reading objects from a file using Serializable:

    public ArrayList<Object> deserialzePerson(String filename) {
    Object obj = null;
    ObjectInputStream ois;
    try {
        ois = new ObjectInputStream(new FileInputStream(filename));
        for (int i = 0; i < 100; i++) {
            obj = (Object) ois.readObject();
            ObjectArray.add(obj);
        }
    } catch (Exception e) {
    }
    return ObjectArray;
}

However, I do not know the amount of objects in the file and use the number "100" in the for-loop. If there are less than 100, the exception will kick in and everything goes as expected. Nevertheless, I find this solution poor because it depends on catching errors. Is there a way to set the limit of the for-loop for the amount of objects in the file?

For instance, when reading from a .txt file I used .hasNext(); is there something like this for objects?


Solution

  • public void serializePerson(String filename, List<Person> persons) {
        try (FileOutputStream fos = new FileOutputStream(filename);
             ObjectOutputStream ous = new ObjectOutputStream(fos)) {
    
            ous.writeInt(persons.size());
            for (Person person : persons) {
                ous.writeObject(person);
            }
        } catch (Exception e) {
        }
    }
    
    public List<Person> deserializePerson(String filename) {
        List<Person> result = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(filename);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            int size = ois.readInt();
            for (int i = 0; i < size; i++) {
                Person person = (Person) ois.readObject();
                result.add(person);
            }
        } catch (Exception e) {
        }
        return result;
    }