-3

I'm having problems with saving text to a file, I'm saving text from text fields to a file. The text fields are saving to the file fine, but when I close the program re-open it and try to save a new entry, it wipes the file and corrupts it. Help would be greatly appreciated :)

        // BUTTON SAVE ------------------------------------------
    if(e.getSource() == btnSave)
    {
        // Call the saveEntry method that will copy the current
        // TextField entries from the screen to the current
        // record in the array in memory.
        saveEntry(currentEntry);
    }


public void saveEntry(int i) // 
{
    PersonsInfoData[i].setPersonsInfo(txtPersonsName.getText(),txtLikes.getText(),txtDislikes.getText(), txtBdayDay.getText(), txtBdayMonth.getText()); 

    // You may also wish to write all the records that are currently in the array
    //       to your data file on the hard drive (USB, SSD, or equivalent)
    writeFile(dataFileName);
}


public void writeFile(String fileName)
{
    try
    {

        PrintWriter printFile = new PrintWriter(new FileWriter("BirthdayTracker.txt"));   

        for(int i = 0; i < numberOfEntries; i++)
        {
            printFile.println(PersonsInfoData[i].getPersonsName() + "," + PersonsInfoData[i].getPersonsLikes() + "," + PersonsInfoData[i].getPersonsDislikes()  + "," + PersonsInfoData[i].getBdayDay() + "," + PersonsInfoData[i].getBdayMonth() );
        }

        printFile.close();
    }
    catch (Exception e)
    {
        System.err.println("Error Writing File: " + e.getMessage());
    }
Joel
  • 9
  • 2
  • It might have something to do with not using the `filename` you pass to `writeFile` and instead use a hardcoded file name. What do you expect other than the file getting overwritten? – Filburt Apr 19 '17 at 07:19

1 Answers1

1

You should create the FileWriter object in append mode like below

new FileWriter("BirthdayTracker.txt", true);

Anil Agrawal
  • 2,748
  • 1
  • 24
  • 31