Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store new values in existing csv file in Android?

Tags:

android

I am working on an ANDROID project where i have to create a CSV file from some data. I am able to create csv file and store data by creating Captions.

Code Snippet for that is given Below::

package com.csvtry;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class csvtry extends Activity {
    public static String abc=null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        generateCsvFile("Example1.csv"); 

    }
    private static void generateCsvFile(String sFileName)
    {
        try
        {
            File root = Environment.getExternalStorageDirectory();
            File gpxfile = new File(root, sFileName);
            FileWriter writer = new FileWriter(gpxfile);

            abc="Guwahati";

            writer.append("Emp_Name");
            writer.append(',');
            writer.append("Adress");
            writer.append('\n');

            writer.append("hussain");
            writer.append(',');
            writer.append("Delhi");
            writer.append('\n');

            //generate whatever data you want

            writer.flush();
            writer.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        } 
     }
}

As in above code, we can see, Example1.csv is created and stored in SDCARD. I works absolutely fine....

But i want to write some new data in new rows and columns in Example1.csv.

But when i try to run emulator again with some new data, it replaces existing row data.

My question is that, how can we write new data in new row without replacing previous data? How to write new data in new rows ???

I am stuck on this...Please give me suggestions how to proceed ..

Thanks in advance....

like image 339
mH16 Avatar asked May 13 '11 08:05

mH16


1 Answers

You can try using

FileWriter(String filename, boolean append)

to append data to the end of the file

like image 107
Alok Avatar answered Nov 06 '22 04:11

Alok