Louise Kaithlyn
Louise Kaithlyn

Reputation: 47

Use an arraylist in file input output java

So, here is the question. I want to create a file using java GUI, this is something like the user can create an account or login in my GUI, and then their account becoming file.txt in mine. But, I have a problem here. When I create an account in my GUI, it works well, and the file is created. But, when I tried to create an account again, an account that have been created before is gone. So, I guess I need to use arraylist in this case, and I use it, but it still doesn't work. Here is the code :

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");
    }

}

And this is the action :

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) {

    }

Upvotes: 1

Views: 362

Answers (1)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

You have FileWriter fw = new FileWriter(filename);

So your file is overridden over and over every time your function is called.

So you have two options:

  1. Store one credential to each setting file name. (you can distinguish the file by appending username to your settings file, for example)
  2. Store all credential to settings file. But you have to open your file in append mode

        FileWriter fw = new FileWriter(filename, true); // true flag indicate appending mode
    

    And you have to change your reading side too, since your settings file now store all credential.

Upvotes: 1

Related Questions