Can’t save and load an object to file

I guess I don’t even have to mention that I am a beginner with Java, and that this is part of an assignment. It has to be pretty obvious. What I want is to count occupied rooms in an apartment booking system, but I am totally stuck. I really can’t figure out how to save the value of aptA, aptB and aptM. I need them to load every time I restart the program. Right now I’m getting the following error:

Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – Erroneous sym type: ObjectInputStream at apartments1.Person.loadObject(Person.java:348) at apartments1.Booking.main(Booking.java:24) Java Result: 1

I have a feeling my approach to this might be way wrong though, but this is were I ended up after desperately testing several other solutions… Now it’s all a big mess, and I’m about to give up.

     //creating the object   
     public static void addRoomCounter(){
     Person roomCounter = new Person(); 
     roomCounter.addAptA();
     roomCounter.addAptB();
     roomCounter.addAptM();

     //adding it to arraylist
    ArrayList<Person> roomList = new ArrayList<Person>();
roomList.add(roomCounter);

    //saving it to file
     try{
     FileOutputStream saveFile = new FileOutputStream("Roomcounter.txt");
     ObjectOutputStream save = ObjectOutputStream(saveFile); //cannot find symbol
     save.writeObject(roomCounter);
     save.close();
    }catch(Exception exc){
    }
    }


    public int addAptA(){
    return aptA;
    }
    public int addAptB(){
    return aptB;
    }
    public int addAptM(){
    return aptM;
    }

    //loading object
public static void loadObject(){
    try{
    FileInputStream saveFile = new FileInputStream("Roomcounter.txt");
ObjectInputStream restore = ObjectInputStream(saveFile); //cannot find symbol
Object roomCounter = restore.readObject();
    int aptA = (int) restore.readObject();
    int aptB = (int) restore.readObject();
    int aptM = (int) restore.readObject();
restore.close();
    }catch(IOException | ClassNotFoundException exc){
    }
    }

Answer

The issue is with your reading block. You are reading the object but type-casting it to int where it should be Person. i.e.

public static void loadObject(){
try{
  FileInputStream saveFile = new FileInputStream("Roomcounter.txt");
  ObjectInputStream restore = ObjectInputStream(saveFile); //cannot find symbol
  Person roomCounter = (Person) restore.readObject();
  int aptA = (int) restore.getAptA();
  int aptB = (int) restore.getAptB();
  int aptM = (int) restore.getAptC()();
  restore.close();
  }catch(IOException | ClassNotFoundException exc){
   exc.printStackTrace();
}
}

In your example, you were reading the object thrice from the serialized object on file. Rather you need to read it once and then work around.

Leave a Reply

Your email address will not be published. Required fields are marked *