我试图存储用户输入的数据并将其存储在文本文件中以便以后操作,我有问题继续覆盖数据代码的第一行下面:
public void AddDataToFile(int i)
{
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./Cat Info.txt"));
Cat catCurrent;
catCurrent = catPenArray [i];
writer.append("Pen Number " + (i + 1));
writer.newLine();
writer.write("Cat Name " + catCurrent.CatName);
writer.newLine();
writer.write("Cat Gender " + catCurrent.Gender);
writer.newLine();
writer.write("Chip Number " + catCurrent.ChipNumber);
writer.newLine();
writer.write("Arival Date " + catCurrent.ArrivalDate);
writer.newLine();
writer.write("Departure Date " + catCurrent.DepartureDate);
writer.newLine();
writer.write("How often fed " + catCurrent.HowOftenFed);
writer.newLine();
writer.write("Type Of food " + catCurrent.Food);
writer.newLine();
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
}
答案 0 :(得分:2)
BufferedWriter
不是问题 - 这就是你构建FileWriter
的方式。您只需使用constructor overload which takes an append
parameter:
new FileWriter("./Cat Info.txt", true)
我个人会尽量避免使用FileWriter
:它不允许您指定编码,这意味着它将始终使用平台默认编码。我更喜欢使用FileOutputStream
,并将其包装在OutputStreamWriter
中,明确指定编码(通常为UTF-8)。同样,FileOutputStream
有一个构造函数,允许您追加而不是覆盖。