我已经创建了一个 onLoad 方法来在我的程序中使用序列化,但我想同时使用一个 onSave 方法,以便在程序关闭并再次启动时,我不必一次又一次地填充我的 Jlist。
我已经尝试创建自己的 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;
}