2017-04-19 84 views
-3

我在將文本保存到文件時遇到問題,我正在將文本從文本字段保存到文件中。文本字段保存到文件中,但是當我關閉程序時,重新打開它並嘗試保存一個新條目,它擦除該文件並將其損壞。幫助將不勝感激:)將文本保存到文件時出現問題

 // 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()); 
    } 
+0

它可能與不使用傳遞給writeFile的'filename'有關,而是使用硬編碼的文件名。除了文件被覆蓋以外,你還期望什麼? – Filburt

回答

1

您應該創造附加模式的FileWriter對象像下面

新的FileWriter( 「BirthdayTracker.txt」,真正的);

+0

如果您的問題得到解決,您可以接受答案 –

相關問題