从文件读取保存的数组列表(对象)时发生类异常

问题描述 投票:1回答:1

我想从文件中实际读取数据到Flight_registrie类的数组列表中。我能够将数组列表保存在文件中,但是当我尝试从文件中读取时,它无法正常工作并给出类强制转换异常。我也尝试直接在数组列表中获取值,但是没有用。您能告诉我应该怎么写才能将文件中的数据读取到数组列表中吗?

try {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(" Flight Registrie.bin"));

    Flight_registrie b =(Flight_registrie) ois.readObject();
    alr.add(b);
    ois.close();
} catch (FileNotFoundException e) {
    System.out.println("\t\t\tFile not Found.");    
} catch (IOException e) {
    System.out.println("An I/O error occurs");
} catch (ClassNotFoundException e) {
    System.out.println("\t\tClass Flight_registrie not found ");
}

和下面的代码是我如何输入的。

try {al.add(a);
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(" Flight Registrie.bin"));
    oos.writeObject(al);
    System.out.println("Data Saved");
    al.clear();
oos.close();
} catch (IOException e) {
System.out.println("An I/O error occurs");
}

错误:

 Exception in thread "main" java.lang.ClassCastException: class
java.util.ArrayList cannot be cast to class
source__module.Flight_registrie (java.util.ArrayList is in module
java.base of loader 'bootstrap'; source__module.Flight_registrie is in
unnamed module of loader 'app')
    at source__module.Functions.get_data(Functions.java:64)
    at file.Launcher.main(Launcher.java:41)
java arraylist classcastexception objectinputstream
1个回答
0
投票

似乎您正在将列表保存在文件中。但是在阅读时,您正在尝试将列表读入Flight_registrie。

这就是为什么在尝试将ArrayList对象强制转换为Flight_registrie类的对象时出现错误的原因。错误的行是:

 Flight_registrie b =(Flight_registrie) ois.readObject();

尝试将其更改为此:

List<Flight_registrie> b =(List<Flight_registrie>) ois.readObject();

这应该可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.