Ashna Khan
Ashna Khan

Reputation: 3

getting exception during deserialization

public List<Show> populateDataFromFile(String fileName)
 {
    List<Show> shows= null;
    try{
        ObjectInputStream in=new ObjectInputStream(new FileInputStream(fileName));
        shows= (List<Show>) in.readObject();
       in.close();

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }


      return shows;

 }

I'm getting java.lang.ClassCastException: com.bean.Show cannot be cast to java.util.List

I've performed deserialization to initialise data of show class that is already serialized. I also make show class as serializable by implementing serializable i/f. I think readObject method can't convert into ArrayList.. Please tell me how do I convert it?

Upvotes: 0

Views: 196

Answers (2)

Dima
Dima

Reputation: 40500

What you've written in the file, must be an instance of the Show class, not a List<Show>. Perhaps, instead of outputStream.writeObject(list); you did something like for(Show show: list) outputStream.writeObject(show);? Try reading it back the same way:

List<Show> shows = new ArrayList<Show>();
try {
    while(true) {
        shows.add((Show) in.readObject());
} catch (EOFException e) {
   in.close();
   // end of file
}

Upvotes: 1

A4L
A4L

Reputation: 17595

Apparently the Object you have serialized is a single object of Show and not a List of Shows as you are expecting, try to cast to Show only or check your serialization and make sure you are serializing a List<Show>.

Upvotes: 0

Related Questions