2016-06-10 91 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

我认为是的,这是我的代码。 –