OnSave方法使用onload方法?

时间:2013-04-26 09:08:01

标签: java serialization

我已经创建了一个onLoad方法来在我的程序中使用序列化,但是我想使用onSave方法,因此当程序关闭并重新启动时,我不必一次又一次地填充我的Jlists。 / p>

我已经尝试创建自己的onSave函数,但是无法在任何附近工作。

有人可以给我看一个例子,或者给我一个onSave函数,让我的序列化工作有效。

这是我的onLoad()方法:

private void onLoad()
    {//Function for loading patients and procedures
        File filename = new File("ExpenditureList.ser");
        FileInputStream fis = null;
        ObjectInputStream in = null;
        if(filename.exists())
        {
            try {
                fis = new FileInputStream(filename);
                in = new ObjectInputStream(fis);
                Expenditure.expenditureList = (ArrayList<Expenditure>) in.readObject();//Reads in the income list from the file
                in.close();
            } catch (Exception ex) {
                System.out.println("Exception during deserialization: " +
                        ex); 
                ex.printStackTrace();
            }
        }

这是我对onSave方法的尝试:

try
              {
                 FileInputStream fileIn =
                                  new FileInputStream("Expenditure.ser");
                 ObjectInputStream in = new ObjectInputStream(fileIn);
                 expenditureList = (ArrayList<Expenditure>) in.readObject();


                 for(Expenditurex:expenditureList){
                        expenditureListModel.addElement(x);
                     }


                 in.close();
                 fileIn.close();
              }catch(IOException i)
              {
                 i.printStackTrace();
                 return;
              }catch(ClassNotFoundException c1)
              {
                 System.out.println("Not found");
                 c1.printStackTrace();
                 return;
              }

1 个答案:

答案 0 :(得分:0)

您只需写入ObjectOutputStream:

public void onSave(List<Expenditure> expenditureList) {
    ObjectOutputStream out = null;
    try {
        out = new ObjectOutputStream(new FileOutputStream(new File("ExpenditureList.ser")));
        out.writeObject(expenditureList);
        out.flush();
    }
    catch (IOException e) {
        // handle exception
    }
    finally {
        if (out != null) {
            try {
                out.close();
            }
            catch (IOException e) {
                // handle exception
            }
        }
    }
}

public List<Expenditure> onLoad() {
    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(new FileInputStream(new File("ExpenditureList.ser")));
        return (List<Expenditure>) in.readObject();
    }
    catch (IOException e) {
        // handle exception
    }
    catch (ClassNotFoundException e) {
        // handle exception
    }
    finally {
        if (in != null) {
            try {
                in.close();
            }
            catch (IOException e) {
                // handle exception
            }
        }
    }
    return null;
}