javaarraylistclasscastexceptionobjectinputstream

Class cast Exception when reading an saved array list (object) from a file


I want to actually read data from a file into an array list of a Flight_registrie class. I am able to save an array list in a file, but when I try to read from the file, it's not working and giving a class cast exception. I also tried to get values in the array list directly, but it didn't work. Can you tell me what should I write to read data from a file into an array list?

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

and below code is how i took input .

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

Error:

 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)

Solution

  • Seems like you are saving a List in your file. But while reading you are trying to read a List into Flight_registrie.

    That id why the error is coming as you are trying to cast an ArrayList object into and object of Flight_registrie class. The faulty line is :

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

    Try changing it to this :

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

    And this should fix the problem.