简体   繁体   English

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

[英]How do I write an object to a file and read it back?

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 (); 我对这一行代码有Vehicule result = (Vehicule) read.readObject ();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. 谢谢您的帮助。

似乎您正在编写List<Vehicule>但阅读了Vehicule

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何将对象的数据写入文件,然后在读取文件时将其解析回新的对象 - How do I write the data of an object to a file and then parse it back into a new object when the file is read 如何写回.txt文件? - How do I write back to a .txt file? 在Java中,如何将对象写入文件,然后再从文件中读取该对象并将其转换回HDFS中的原始对象? - In java, how to write an object to a file and later on read it from the file and convert it back to the original object in the HDFS? 如何写入/读取已锁定的文件? - How do I write/read to a file that I've locked? 在Java中,如何写入我最近读取的文件? - In Java, how do I write to a file I recently read from? 从 JSON 文件中读取并在向该对象添加属性后写回它 - Read From JSON File and after adding a property to that object write back to it 如何从Java中的ArrayLists读取和写入文件 - How do I read and write a file from ArrayLists in Java 如何使用Java中的线程读写文件? - How do I read and write to a file using threads in java? 如何在文件中读写对象的数组列表的数组列表? - How do I Read/Write an ArrayList of Arraylists of Objects to/from a file? Java如何读取和写入内部属性文件? - Java How do I read and write an internal properties file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM