如何在Java中保存和加载对象?我试过了,但它一直在抛出IOexception

时间:2014-10-03 11:54:11

标签: java serialization


public class DriverClass implements Serializable {
    CafeManager cafe = new CafeManager(); - Creates the object 

    public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException{
        CafeManager newcafe;

        newcafe = load(); - Calls the load module

        SystemMenu menu = new SystemMenu();
        menu.displaymenu(); - Running of the menu


        newcafe = new CafeManager(newcafe.getMenuItems(),newcafe.getOrders()); - Once the user exits the menu, file should be saved


        save(newcafe);

    }

    public static void save(CafeManager newcafe) throws FileNotFoundException, IOException{
        try{
            FileOutputStream fileOut = new FileOutputStream("system.dat");

            ObjectOutputStream out = new ObjectOutputStream(fileOut);

            out.writeObject(newcafe);
        }
        catch (FileNotFoundException fe){
            System.out.println("File Not found.");
        }
        catch (IOException ie){
            System.out.println("File Crappy" + ie.getMessage()); //Output: File Crappycafesys.Order
        }

    }

    public static CafeManager load() throws FileNotFoundException, IOException, ClassNotFoundException{
        CafeManager curcafe = new CafeManager();
        FileInputStream fileIn = new FileInputStream("system.dat");

        ObjectInputStream in = new ObjectInputStream(fileIn);

        try{
            curcafe = (CafeManager) in.readObject();
        }
        catch(ClassCastException | ClassNotFoundException ce){
            //
        }
        catch (FileNotFoundException fe){
            System.out.println("File Not found.");
        }
        catch (IOException ie){
            System.out.println("File Crappy" + ie.getMessage()); //Output: File Crappy writing aborted; java.io.NotSerializableException: cafesys.Order
        }

        return curcafe;
    }

我不确定为什么IOException被抓住了。正如我创建了文件并通过ObjectOutputStream运行它。异常消息是:

  

java.io.NotSerializableException: cafesys.Order

0 个答案:

没有答案