无法保存并加载对象到文件

时间:2013-07-12 19:33:54

标签: java objectoutputstream

我想我甚至不必提及我是Java的初学者,这是作业的一部分。它必须非常明显。我想要的是计算公寓预订系统中的占用空间,但我完全陷入困境。我真的无法弄清楚如何保存aptA,aptB和aptM的价值。我每次重新启动程序时都需要加载它们。现在我收到以下错误:

  

线程“main”中的异常java.lang.RuntimeException:Uncompilable   源代码 - 错误的sym类型:ObjectInputStream at   apartments1.Person.loadObject(Person.java:348)at   apartments1.Booking.main(Booking.java:24)Java结果:1

我有一种感觉,我对此的处理方式可能有点错误,但这是我在拼命测试其他几种解决方案之后最终结果......现在这一切都很糟糕,我即将放弃。

     //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){
    }
    }

1 个答案:

答案 0 :(得分:1)

问题在于您的阅读障碍。您正在阅读该对象,但将其输入到int,其位置应为Person。即。

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

在您的示例中,您正在从文件中的序列化对象中读取对象三次。相反,你需要阅读一次,然后解决。