在文件输入输出中使用数组列表 java

Use an arraylist in file input output java

那么,问题来了。我想使用 java GUI 创建一个文件,这类似于用户可以在我的 GUI 中创建帐户或登录,然后他们的帐户在我的帐户中变为 file.txt。但是,我这里有问题。当我在我的 GUI 中创建一个帐户时,它运行良好,并创建了文件。但是,当我再次尝试创建帐户时,之前创建的帐户消失了。所以,我想在这种情况下我需要使用 arraylist,我使用了它,但它仍然不起作用。这是代码:

String filename="D:/settings.txt";

public void getIdentity() throws FileNotFoundException, IOException{
    File file = new File(filename);
    ArrayList identity = new ArrayList();

    String fullname = txt_fullname.getText();
    String username = txt_username.getText();
    String password = pass_password.getText();

    try {
        FileWriter fw = new FileWriter(filename);
        Writer output = new BufferedWriter(fw);

        identity.add(fullname + "-" + username + "-" + password);

        for (int i = 0; i <identity.size(); i++)
        {
         output.write(identity.get(i).toString() + "\n");
        }
        output.close();
    }


    catch (Exception ex)
    {
        JOptionPane.showMessageDialog(null, "Cannot create a file");
    }

}

这是动作:

try {

        if(txt_username.getText() != null && pass_password.getText() != null
           && txt_fullname.getText() != null)
        {
        getIdentity(); 
        JOptionPane.showMessageDialog(null, "Congratulations, you've created a file");
        this.setVisible(false);
        Login login = new Login();
        login.setVisible(true);
        }
        else {
            JOptionPane.showMessageDialog(null, "Please fill in your identity");
        }
    } catch (IOException ex) {

    }

你有FileWriter fw = new FileWriter(filename);

因此每次调用您的函数时,您的文件都会被一遍又一遍地覆盖。

所以你有两个选择:

  1. 为每个设置文件名存储一个凭据。 (例如,您可以通过将用户名附加到您的设置文件来区分该文件)
  2. 将所有凭据存储到 settings 文件。但是您必须以 append 模式

    打开文件
        FileWriter fw = new FileWriter(filename, true); // true flag indicate appending mode
    

    而且你也必须改变你的阅读方,因为你的设置文件现在存储了所有凭证。