java - 从包含多个对象的序列化文件中读取数据

标签 java deserialization

我正在尝试从包含类的多个对象的文件中读取数据。但是我在将对象添加到列表时遇到空指针异常。有人可以帮忙吗?

代码如下:

//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);
    }
    }   
}

}

最佳答案

每次迭代都会读取对象三次。

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

关于java - 从包含多个对象的序列化文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30724037/

相关文章:

java - 有没有办法使用 Apache POI 为 docx 文件设置固定元数据?

garbage-collection - 确定 OpenJDK Activity GC 类型

java - 创建 EntityManagerFactory 时出现 ArrayIndexOutOfBoundsException

java - 为什么 hasNextInt() 在这里返回 false?

spring-boot - Spring Boot Jackson - 日志记录

java - Java序列化可以与加密相媲美吗?

c# - 二进制序列化和自动属性

java - GSON 反序列化为 ArrayList<T> 不起作用

java - 序列化和反序列化未实现 java.io.Serializable 的对象

java - 无法访问的 Java 代码