1

我已经创建了一个 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;
              }
4

1 回答 1

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;
}
于 2013-04-26T09:52:56.070 回答