从文件中读取ArrayList作为对象?

时间:2013-01-05 15:16:12

标签: java io

好吧,所以我做了以下事情:

  1. 我已将对象添加到ArrayList,并将整个列表作为对象写入文件。

  2. 问题在于尝试将它们作为一个整体读回来。我收到以下错误:

  3. 线程“main”中的异常java.lang.ClassCastException:java.util.Arrays $ ArrayList无法强制转换为java.util.ArrayList     在persoana.Persoana.main(Student.java:64)

    这是我的代码:(一切都在尝试捕获所以没有什么可担心的)

    编写

    Student st1 = new Student("gigi","prenume","baiat","cti");
            Student st2= new Student("borcan","numegfhfh","baiat cu ceva","22c21");
    
            List <Student> studenti = new ArrayList<Student>();
            studenti = Arrays.asList(st1,st2);
    
    FileOutputStream  fos = new FileOutputStream("t.ser");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
    
                oos.writeObject(studenti);
                oos.close();
    

    FileInputStream fis = new FileInputStream("t.ser");
                 ObjectInputStream ois = new ObjectInputStream(fis);
    
                 ArrayList <Student> ds;
    
                 ds = (ArrayList <Student>)ois.readObject(); 
    
                 ois.close();
    

    问题出现在这一行:

    ds = (ArrayList <Student>)ois.readObject();
    

2 个答案:

答案 0 :(得分:9)

我想问题是您正在创建List StudentArrays.asList。此方法不返回ArrayList,而是返回Arrays.ArrayList这是一个不同的类,用于支持数组并能够将其用作ListArrayListArrays.ArrayList都实现了List接口,但它们不是同一个类。

您应该将其投射到适当的对象:

List<Student> ds = (List<Student>)ois.readObject();

答案 1 :(得分:4)

更改以下行:

ArrayList <Student> ds;
ds = (ArrayList<Student>)ois.readObject(); 

List<Student> ds = (List<Student>)ois.readObject();