Reputation: 2003
I am saving some csv to a file on the local android storage.I want to append new lines to existing csv file but my code overwrites the previous data and I can see just a single line of csv text.Please guide where I am going wrong.Here is my current code.
private void saveLogFile(Long activityTimestamp, Long currentTime,
Integer activityType) {
if (activityTimestamp != null && currentTime != null
&& activityType != null) {
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/ACTIVITY_RECOGNITION");
dir.mkdirs();
File myFile = new File(dir, "activity_log.csv");
try {
if (!myFile.exists()) {
myFile.createNewFile();
}
if (myFile.exists()) {
CSVWriter writer = new CSVWriter(new FileWriter(myFile));
//List<String[]> data = new ArrayList<String[]>();
//data.add(new String[] { activityTimestamp.toString(),currentTime.toString(), activityType.toString() });
String[] data={ activityTimestamp.toString(),currentTime.toString(), activityType.toString() };
writer.writeNext(data);
writer.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.d("saveLogFile", "some data is null");
}
}
Upvotes: 1
Views: 408
Reputation: 3956
See Java Docs, use FileWriter(File file, boolean append);
that is:
CSVWriter writer = new CSVWriter(new FileWriter(myFile, true));
Upvotes: 1