luckysing_noobster
luckysing_noobster

Reputation: 2003

Cannot append new line string to a file Android local storage

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

Answers (2)

Software Engineer
Software Engineer

Reputation: 3956

See Java Docs, use FileWriter(File file, boolean append); that is:

CSVWriter writer = new CSVWriter(new FileWriter(myFile, true));

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157447

Chante

new FileWriter(myFile)

to

new FileWriter(myFile, true)

the second parameter is the append flag. Here you can find the documentation

Upvotes: 2

Related Questions