0

I want to construct an object which has the following behavior :

If the file 'save_object' is empty or doesn't exist create the default object else get back the object that is in the file

I know I will use the Serialization How to write and read java serialized objects into a file But I want to do it IN the class and I don't know how to do it.

I tried with this code (Sorry I just have a part, if it's needeed, I'll the rest as soon as I can)

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

I have a problem with this = (Garage)ois.readObject(); and I don't know how to manage it. I have some ideas but all of them are about do one attribut by one and if it's possible, I prefer to avoid to do that

user207421
  • 305,947
  • 44
  • 307
  • 483
Ccile
  • 187
  • 1
  • 3
  • 12

1 Answers1

1

your class is getting complicated and wrong developed because you are not splitting the responsibilities of every module in the app, what you are trying to do must be the work of some GarageManager class, that class is the responsible for checking if the file exist or not aswell as giving you a garage object (either new created or restored/deserialized from disk)

and example of how that manager can look like is:

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;
    }
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 1
    Ok in general app. Here, it's an exercise (sorry in French http://exercices.openclassrooms.com/assessment/63?login=291463&tk=bb5924474ed7ca20fd3bb5d200e1431a&sbd=2016-02-01&sbdtk=fa78d6dd3126b956265a25af9b322d55 ) And there is no GarageManager – Ccile Aug 11 '17 at 09:13