如何反序列化并将获得的数据传输到ArrayList?

问题描述

我正在尝试(反)序列化一个简单的序列化文件,称为“ people.dat”,其中包含人员数据(“姓名”,“年龄”,“邮件”等)并将所有行(person1数据,person2数据等)传输到ArrayList。

类似这样的东西:


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


它向我发送“ ClassNotFoundException”行

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

我的问题是:

1-我在做什么错了?

2-(对于初学者而言)将那些数据从.dat文件->传递到ArrayList的最佳方法是什么?

谢谢..

解决方法

可能的原因是,序列化Person的类路径与尝试反序列化时的Person的类路径不同。

会抛出错误的示例:

  • 序列化时Person的类路径是app.package.Person
  • 在尝试反序列化时,Person的类路径现在为app.Person

这不起作用,因为在序列化文件中写入了“原始”类路径。

此外,您确切地序列化了什么?包含Persons的ArrayList或者只是一个Person,而您正试图直接在ArrayList中反序列化它(不可能)?

如果要反序列化到ArrayList中,则该东西必须是已序列化的ArrayList! (因为是的,您可以序列化ArrayList,因为它只是一个类!)