2013-04-26 242 views
1

我創建了一個在我的程序中使用序列化的onLoad方法,但是我想使用onSave方法以及程序關閉並重新啓動,我不必一次又一次地填充我的Jlists。OnSave方法使用onload方法?

我試過創建我自己的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; 
       } 
+0

什麼你的onSave方法看起來像嗎? – Fildor 2013-04-26 09:15:21

+0

這是正確的片段嗎?您正在使用* Input * Streams。 – Fildor 2013-04-26 09:29:25

+0

它們應該是輸出流。不知道我在onSave方法上做了什麼,希望有人能幫助我。 – 2013-04-26 09:30:20

回答

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; 
} 
+0

我會在哪裏實現這些方法?在一個按鈕或主要。我已經嘗試添加到主要和兩個按鈕,但是當這完成後,序列化文件永遠不會創建? – 2013-04-26 16:28:06

+0

我不知道你的應用程序的體系結構,但我想:''onLoad()'應該在'main()'方法中調用'onSave()',每當你退出應用程序。看[這個答案](http://stackoverflow.com/a/2361567/1277252)。 – 2013-04-27 13:44:23