0

Hi I'm creating a program which takes the data from a GUI form and then saves the data to a text file. I want each record to save as a new line in the text file, however a new record just overwrites the existing record in the file. I've tried using /n to set a new line and bufferedWriter.newline(); both of which set up an empty new line but the new record still overwrites the existing one.

The below code shows the action listener for the save button and then the ToString class is where I save over the records to a text file. I suspect my issue is something to do with the way I have used the child constructor, every child obviously overwrites the previous but I want to avoid this.

public class save implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {

            String name = JTextFieldname.getText();
            String date = JTextFielddateofbirth.getText();
            String address = JTextFieldaddress.getText();
            String allergy = JTextFieldallergy.getText();
            String contactno = JTextFieldparentcontactno.getText();

            child b = new child(name,date,address, allergy, contactno);
            ToString(b);

        }
    }

    public static void ToString(child child){
        System.out.println(child.getName() + " " + child.getDate() + " " + child.getAddress() +" " + child.getAllergy()+" " + child.getContactno()  );
        try {
            BufferedWriter writer = new BufferedWriter ( new PrintWriter (".\\child.txt"));
            writer.write(child.getName() + " " + child.getDate() + " " + child.getAddress() +" " + child.getAllergy()+" " + child.getContactno() );
            writer.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

Thanks in advance! I'm using jre 1.8 by the way.

Ollie Atkins
  • 133
  • 1
  • 5
  • 14

0 Answers0