如何将对象写入文件并将其读回?

时间:2017-11-13 14:22:10

标签: java file serialization

我需要你的帮助,因为我想在文件中写一个对象并将其读回来。

我对这行代码有疑问: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();
   }

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您似乎正在撰写List<Vehicule>,但请阅读Vehicule