reading data from a serialized file containing multiple objects

373 views Asked by At

I'm trying to read data from a file containing multiple objects of a class. But I'm getting null pointer exception while adding objects to list. can anyone help?

Here's the code:

//I'm following the same approach, but getting null Pointer exception while 
//adding the object to a list. I'll post my code below. Can anyone help?

public class DeserializingMultipleObjects {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
   //create few objects of student class and serialize them in a single file

    Student st1= new Student(1, "abhishek", 24, 1);
    Student st2= new Student(2, "Prashant",23,3);
    Student st3= new Student(3,"Gayatri",22,2);
    Student st4= new Student(4,"Ankul",23,4);

    FileOutputStream fout= null;
    FileInputStream fin= null;
    ObjectInputStream oin=null;
    ObjectOutputStream oout= null;
    List <Student> studentList=null;

    try{
    fout= new FileOutputStream("Student.ser");
    oout= new ObjectOutputStream(fout);
    oout.writeObject(st1);
    oout.writeObject(st2);
    oout.writeObject(st3);
    oout.writeObject(st4);

    //objects have been serialized. Now read them and populate in a list

    fin= new FileInputStream("Student.ser");
    oin= new ObjectInputStream(fin);
    boolean flag=false;

    while(!flag){
        if(oin.readObject()==null || oin.readObject().equals("")){
        flag=true;
        }
        else{
        studentList.add((Student)oin.readObject());
        }
    }


    }

    catch (ClassNotFoundException ex) {
        Logger.getLogger(DeserializingMultipleObjects.class.getName()).log(Level.SEVERE, null, ex);
    }        finally{
    if(fout !=null) try {
        fout.close();
    } catch (IOException ex) {
        Logger.getLogger(DeserializingMultipleObjects.class.getName()).log(Level.SEVERE, null, ex);
    }
    if(oout !=null){
    oout.close();
    }
    if(fin !=null){
    fin.close();
    }
    if(oin !=null){
    oin.close();
    }

     for(Student student: studentList){

        System.out.println(student.name);
    }
    }   
}

}
3

There are 3 answers

1
blueygh2 On BEST ANSWER

List <Student> studentList=null; is giving the error. When you reach the part where you want to add to studentList with studentList.add((Student)oin.readObject());, the list is a null pointer because you initialized it as such.

You might want to initialize the list to something else than null, e.g. List<Student> studentList = new ArrayList<Student>();

0
Orest Savchak On

You read your object three times per iteration.

while(!flag){
    Student st = oin.readObject();
    if(st == null){
        flag=true;
    }
    else{
       studentList.add(st);
    }
}
1
JB Nizet On

Several mistakes:

  1. You forgot to close the ObjectOutputStream before starting to read from the file
  2. Every time you call readObject(), you read the next object from the stream, so the following lines:

    if(oin.readObject()==null || oin.readObject().equals("")){
        flag=true;
    }
    else{
        studentList.add((Student)oin.readObject());
    }
    

read 2 or three objects, instead of reading just one. They should be

    Object read = oin.readObject()
    if(read == null || read.equals("")){
        flag=true;
    }
    else {
        studentList.add((Student) read);
    }

But readObject() will never return null, and there's no way it returns an empty string, since you have only written instances of Student in the stream.

Everything would be much easier if you just stored your 4 students in a List<Student> and serilaized this list. Deserializing would simply consist in reading one object (so, no loop necessary): the list of students.

Also, closing the ObjectOutputStream will automatically close the FileOutputStream. Same for the ObjectInputStream. So closing the file streams is unnecessary. For a much cleaner and safer resource handling, you should use try-with-resources.