0

I will need your help because I want to write an object in a file and read it back.

I have a problem with this line of code: Vehicule result = (Vehicule) read.readObject ();

try {
       List<Vehicule> voiture = new ArrayList<Vehicule>();

       //Write object to file 
       FileOutputStream fos = new FileOutputStream("Garage.ser");
       ObjectOutputStream ecriture = new ObjectOutputStream(fos);
       System.out.println("\nIci - Ecriture de mon fichier\n");
       ecriture.writeObject(voiture);
       ecriture.close();
       //read object from file
       FileInputStream fis = new FileInputStream("Garage.ser");
       ObjectInputStream lecture = new ObjectInputStream(fis);
        System.out.println("\nIci - Lecture du fichier\n");
        Vehicule result = (Vehicule) lecture.readObject();
        lecture.close();

   }catch (FileNotFoundException e){
       System.out.println("Aucune voitures sauvegardé !");
   }catch (IOException e) {
       e.printStackTrace();
   }catch (ClassNotFoundException e) {
       e.printStackTrace();
   }

Thank you for your help.

Goibniu
  • 2,212
  • 3
  • 34
  • 38
Toufik
  • 1
  • 5
    The problem is that you are serializing a `List` , and attempting to deserialize it as a `Vehicule` . – Arnaud Nov 13 '17 at 14:26

1 Answers1

2

It seems you're writing a List<Vehicule> but read a Vehicule.

reden
  • 968
  • 7
  • 14
  • Thanks ! How to convert an ArrayList into a String? Is there a method? should I create my own conversion method? – Toufik Nov 13 '17 at 15:51
  • @Toufik : Just write `List result = (List) lecture.readObject();` then acces the content of your list like e.g `Vehicule firstVehicule = result.get(0);` . – Arnaud Nov 13 '17 at 16:00
  • https://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string?rq=1 – reden Nov 14 '17 at 06:22