Home > Software engineering >  How do I deserialize Objects from a file into a list?
How do I deserialize Objects from a file into a list?

Time:11-05

I'm trying to deserialize flat Object(s) from a file, but get this error:

java.lang.ClassCastException: class hausverwaltung.EigentumsWohnung cannot be cast to class java.util.List (hausverwaltung.EigentumsWohnung is in module hausverwaltung of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')

This is my code:

public List<Flat> getFlats() {
    List<Flat> flats = new ArrayList<Flat>();

    try {
        ObjectInputStream reader;
        reader = new ObjectInputStream(new FileInputStream(file));
        flats = (List<Flat>) reader.readObject();
        reader.close();
    } catch (Exception e) {
        System.out.println("Deserialisation error: " e);
        System.exit(1);
    }

    return flats;
}

This is the way how we learned it in class, but I somehow get this error. I tried to find solutions all day and didn't find any... How can I fix this?

CodePudding user response:

reader.readObject reads one object. In your case one Flat.

You are casting a single Flat to List<Flat> which is causing your exception.

To achieve your goal you should read the objects one by one and add them to a list, then return the list.

CodePudding user response:

Try it like this

flats= (Flat) reader.readObject();

It will work if there is one object per file.

EDIT: here's something which is

  •  Tags:  
  • java
  • Related