I'm trying to store data that is being inputted by a user and store it in a text file to be manipulated later on, I'm having problems with it keep on overwriting the first lines on data code below:
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);
}
}
}
}
The BufferedWriter
isn't the problem - it's the way you're constructing the FileWriter
. You can simply use the constructor overload which takes an append
parameter:
new FileWriter("./Cat Info.txt", true)
Personally I would avoid using FileWriter
at all though: it doesn't allow you to specify the encoding, which means it will always use the platform-default encoding. I prefer to use FileOutputStream
, and wrap it in an OutputStreamWriter
, specifying the encoding explicitly (usually as UTF-8). Again, FileOutputStream
has a constructor allowing you to append instead of overwriting.
See more on this question at Stackoverflow