2017-08-11 67 views
0

我想构造一个具有以下行为的对象:如何在Java中保存对象?在反序列化构造

如果文件“save_object”为空或不存在 创建默认对象 其他 找回那就是在物体文件

我知道我会使用序列号How to write and read java serialized objects into a file 但我想在课堂上做,我不知道该怎么做。

我试着用这个代码(对不起,我只是有一个部分,如果它needeed,我会休息,只要我能)

public class Garage implements Serializable 
{ 
    private List<String> cars; 

    public Garage() 
    { 
     File garageFile = new File("garage.txt"); 
     if(!garageFile.exists() || garageFile.length()==0) 
     { 
      cars = new List<String>; 
      System.out.println("Aucune voiture sauvegardée"); 
     } 
     else 
     { 
      ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(garageFile))); 
      this = (Garage)ois.readObject(); 
     } 
    } 
} 

我有this = (Garage)ois.readObject();一个问题,我不知道如何管理它。我有一些想法,但他们都是关于做一个属性,如果可能的话,我宁愿避免这样做

+0

两件事情,我们需要: –

+0

1:邮政编码,所以我们可以检查/复制这里的东西... –

+0

2:***我有一个问题=(车库)ois.readObject(); ***是非常广泛的...错误信息也必须放在这里 –

回答

1

你的课变得越来越复杂,错误的发展,因为你没有把每个模块的责任分开该应用程序,你试图做的必须是一些GarageManager类的工作,该类是负责检查文件是否存在或不给你一个车库对象(新创建或恢复/从磁盘反序列化)

和例子是经理能像为:

class GarageManager { 

    public static Garage GetGarage(String garagePath) 
      throws FileNotFoundException, IOException, ClassNotFoundException { 
     Garage x = null; 
     File garageFile = new File(garagePath); 
     if (!garageFile.exists() || garageFile.length() == 0) { 
      ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(garageFile))); 
      x = (Garage) ois.readObject(); 
      ois.close(); 
     } else { 
      x = new Garage(); 
     } 
     return x; 
    } 
} 
+1

好的一般应用程序。在这里,这是一个练习(对不起,法文http://exercices.openclassrooms.com/assessment/63?login=291463&tk=bb5924474ed7ca20fd3bb5d200e1431a&sbd=2016-02-01&sbdtk=fa78d6dd3126b956265a25af9b322d55) 而且没有GarageManager – Ccile

相关问题