javaarraylistdeserializationobjectinputstream

How to (de)serialize and transfer data obtained to an ArrayList?


I'm trying to (de)serialize a simple serialized file called "people.dat" which contains people data ("Name", "age", "mail",...) and transfer all the lines (person1 data, person2 data,..) to an ArrayList.

Something like this:


import java.io.*;
import java.util.*;

class People implements Serializable{
    protected String _name;
    protected int _age;
    protected String _mail;
    protected String _comments;
    
    public People(String name, int age, String mail, String comments) {
        _name = name;
        _age = age;
        _mail = mail;
        _comments = comments;
    }}


public class Example {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
        if (new File("people.dat").exists()) {      
            try {
                ObjectInputStream ois = new ObjectInputStream (new FileInputStream("people.dat"));
                ArrayList<People> p = new ArrayList<People>();
                p = (ArrayList<People>) ois.readObject();
                System.out.println("Array size is: " + p.size());
            }catch (Exception e){
              e.printStackTrace();
            }
        }}}


It sends me the "ClassNotFoundException" in line

p = (ArrayList<People>) ois.readObject();

My questions are:

1- What am I doing wrong?

2- Which would be the best way (for a beginner) to pass those data from the .dat file -> to the ArrayList?

Thanks..


Solution

  • A possible reason would be that the class path of the class Person was different when you serialized it then when you try to deserialize it.

    Exemple that would throw an error :

    This would not work because in your serialized file, the "raw" class path is written.

    Also, what did you serialize exactly ? An ArrayList containing Persons ? Or just a Person and you're trying to deserialze it directly inside an ArrayList (which in not possible) ?

    If you want to deserialize something into an ArrayList, this something has to be an ArrayList that was serialized ! (Because yes you can serialize an ArrayList as it is just a class !)