0

I am coding a program that requires me to write to an Excel file. I have code that allows me to do this, however, if I try to add more data to the file, it deletes the existing data and replaces it. How do I fix this? My code is shown below:

JButton addClientButton = new JButton("Add");
        addClientButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                PrintWriter pw = null;
                Client newClient = new Client(firstNameTextField.getText(), lastNameTextField.getText(), emailTextField.getText(), phoneTextField.getText(), weightTextField.getText(), heightTextField.getText(), ageSpinner.getValue(), activityLevelComboBox.getSelectedItem());
                try {
                    pw = new PrintWriter(new File("Clients.csv"));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                StringBuilder sb = new StringBuilder();
                sb.append(newClient.getFirst());
                sb.append(",");
                sb.append(newClient.getLast());
                sb.append(",");
                sb.append(newClient.getEmail());
                sb.append(",");
                sb.append(newClient.getPhone());
                sb.append(",");
                sb.append(newClient.getWeight());
                sb.append(",");
                sb.append(newClient.getHeight());
                sb.append(",");
                sb.append(newClient.getClientAge());
                sb.append(",");
                sb.append(newClient.getClientActivity());
                sb.append("\n");

                pw.write(sb.toString());
                pw.close();
            }
        });
Trey Collier
  • 129
  • 2
  • 11
  • See https://stackoverflow.com/questions/8210616/printwriter-append-method-not-appending – Lolmewn Jul 25 '17 at 12:10
  • 1
    See also https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – Lino Jul 25 '17 at 12:10
  • Two things here: A) use your favorite search engine **first** - most often you are not the *first* person to have such a problem B) do **not** do so many things within an action listener. Put your code to write into a file into its own class/method! And have the listener call that method --- but only when we talk about very small things. You should **not** at all run lengthy operations within action listeners - because that blocks the event dispatcher thread. In other words: when you would be saving a large file --- your UI freezes while that happens. – GhostCat Jul 25 '17 at 12:13

0 Answers0