1

プログラムでシリアライゼーションを使用する onLoad メソッドを作成しましたが、これと一緒に onSave メソッドを使用したいので、プログラムを閉じて再起動したときに、Jlists を何度も入力する必要がなくなります。

独自の 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 に答える