我在将文本保存到文件时遇到问题,我将文本字段中的文本保存到文件中。文本字段保存到文件正常,但当我关闭程序重新打开它并尝试保存新条目时,它会擦除文件并破坏它。非常感谢帮助:))
// 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 :(得分:1)
您应该在附加模式下创建FileWriter对象,如下所示
new FileWriter(“BirthdayTracker.txt”,true);