Java 从文件中读取ArrayList作为对象?
好的,我已经做了以下工作:Java 从文件中读取ArrayList作为对象?,java,io,Java,Io,好的,我已经做了以下工作: 我已将对象添加到ArrayList,并将整个列表作为对象写入文件 问题是当试图把它们作为一个整体读回来时。我得到以下错误: 线程“main”java.lang.ClassCastException中的异常:java.util.Arrays$ArrayList不能强制转换为java.util.ArrayList 在persoana.persoana.main(Student.java:64) 这是我的代码:(一切都在尝试捕捉中,所以没什么好担心的) 写作 Student
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();
Student st1=新学生(“gigi”、“prenume”、“baiat”、“cti”);
学生st2=新学生(“博尔坎”、“努梅格夫夫”、“拜厄特-库切瓦”、“22c21”);
List studenti=new ArrayList();
studenti=Arrays.asList(st1,st2);
FileOutputStream fos=新的FileOutputStream(“t.ser”);
ObjectOutputStream oos=新的ObjectOutputStream(fos);
oos.writeObject(studenti);
oos.close();
阅读
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();
FileInputStream fis=新的FileInputStream(“t.ser”);
ObjectInputStream ois=新ObjectInputStream(fis);
ArrayList ds;
ds=(ArrayList)ois.readObject();
ois.close();
问题发生在这一行:
ds = (ArrayList <Student>)ois.readObject();
ds=(ArrayList)ois.readObject();
更改以下行:
ArrayList <Student> ds;
ds = (ArrayList<Student>)ois.readObject();
ArrayList-ds;
ds=(ArrayList)ois.readObject();
到
listds=(List)ois.readObject();
我想问题在于您正在通过数组创建学生的列表。此方法不返回ArrayList
,而是返回Arrays.ArrayList
,它是一个不同的类,用于备份数组并将其用作列表。ArrayList
和Arrays.ArrayList
都实现了List
接口,但它们不是同一个类
您应该将其强制转换为适当的对象:
List<Student> ds = (List<Student>)ois.readObject();
listds=(List)ois.readObject();
Try(学生)ois.readObject();这里有一个注释:List studenti=new ArrayList();studenti=Arrays.asList(st1,st2);您正在浪费ArrayListArrays。asList()
不会返回ArrayList。检查一下它的javadoc,没问题。请参阅Jack的答案,以了解您的原始代码为何不起作用的解释。