2016-06-10 89 views
0
public void openFile(){ 
     try { 
      l = new Formatter("try.txt"); 
      System.out.println("Opened File"); 
     } catch (Exception e){ 
      System.out.println("Did not open file"); 
     } 
    } 
    public void addRecord(){ 
     l.format("%s", nameField.getText()); 
     System.out.println("Added Name" + " " + nameField.getText()); 
     } 
    public void onClose(){ 
     l.close(); 
    } 

/* 

So I am trying to store user data, I have a gui and anytime they click sign up i want to store the namefield in an array list, is it possible that anytime I close and reopen the program and someone else puts in their name it just adds to the array list instead of overriding what the earlier person put in? 
Example is in my gui i type in mike as name, I close it and reopen it and put in john as the name, would that add mike and john or would it be just john? and how do I make them co-exist? 
Thank you 

它將其讀取到文件中,但每次關閉該程序並再次運行它時,它將替換第一行中的任何內容。urenraintity arrayList存儲

回答

1

使用List(其中ArrayList是一個實現),您可以使用add方法。例如,如果您有一個包含單個對象的列表「Mike」,然後執行namesList.add("John")(其中namesListList<String>),那麼列表將包含兩個元素:「John」和「Mike」。

但是,您還提到程序執行之間的持久數據。默認情況下,所有列表純粹是在內存數據存儲,並且將在每次關閉並重新打開程序時清除。要存儲它們,你需要某種形式的數據持久性。在重頭上,這將是一個完整的數據庫,但對於一個簡單需求的小項目,您可以使用SQLite - 甚至只是一個文本文件。

+0

我知道如何使用文本文件來做到這一點,但每當它進入文本文件並關閉並打開文本文件時,文本文件也會發生變化。我被卡住了...... –

+0

聽起來好像你的問題是在首先從文本文件讀取/寫入的代碼中。看看那裏,而不是'ArrayList'代碼。尤其要看你的程序是否在啓動之前立即寫入文件,然後再讀取它。 –

+0

我認爲是的,這是我的代碼。 –