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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14173148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:21:04  来源:igfitidea点击:

Reading ArrayList as object from file?

javaio

提问by Dniel Woody

Alright, so I have done the following:

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

  1. I've added objects to an ArrayList and written the whole list as an object to a file.

  2. The problem is when trying to read them back as a whole. I get the following error:

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

  2. 问题是当试图将它们作为一个整体读回时。我收到以下错误:

Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList at persoana.Persoana.main(Student.java:64)

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

Here's my code: (Everything is in a try catch so nothing to worry about that)

这是我的代码:(一切都在 try catch 中,所以不用担心)

Writing

写作

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

Reading

阅读

FileInputStream fis = new FileInputStream("t.ser");
             ObjectInputStream ois = new ObjectInputStream(fis);

             ArrayList <Student> ds;

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

             ois.close();

The problem occurs at this line:

问题发生在这一行:

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

回答by Hyman

I guess that the problem is that you are creating the Listof Studentthrough Arrays.asList. This method doesn't return an ArrayListbut an Arrays.ArrayListwhich is a different class, meant to backen an Array and to be able to use it as a List. Both ArrayListand Arrays.ArrayListimplement Listinterface but they are not the same class.

我想问题在于您正在创建Listof Studentthrough Arrays.asList。此方法不返回 anArrayList而是Arrays.ArrayList一个不同的类,旨在支持 Array 并能够将其用作List. 双方ArrayListArrays.ArrayList实现List接口,但它们不是同一类。

You should cast it to appropriate object:

您应该将其转换为适当的对象:

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

回答by munyengm

Change the following lines:

更改以下几行:

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

to

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