Monday, July 4, 2016

CSV file read and write in android

CSV WRITE AND READ IN ANDROID

There are many time in android programmers needs to write CSV or export few reports, data in csv format. There are many open source third party libraries available to do this but for the same you can write code without using any third party library.

According to my observation it is better Idea to write own code instead of using third party library like Opencsv libs etc. Generally library is designed to perform multiple task and for the same lots of code used inside library and our requirement is only to read or write csv file then why should we increase our code size to using library.

There is a simple way to read and write CSV without any third party library:


1)      Create a directory to write file

File folder = new File(Environment.getExternalStorageDirectory()
        + "/TestFolder");

boolean var = false;
if (!folder.exists())
    var = folder.mkdir();

System.out.println("" + var);


String fileName = folder.toString() + "/" + "Test.csv";



2)      Writing a CSV file

  FileWriter writer = new FileWriter(fileName);

 writer.append("DisplayName");
 writer.append(',');
 writer.append("Age");
 writer.append('\n');

 writer.append("RAM");
 writer.append(',');
 writer.append("21");
 writer.append('\n');

 writer.append("ROHAN");
 writer.append(',');
 writer.append("22");
 writer.append('\n');


3)      Read CSV file

String []data ;

   FileInputStream fis = new FileInputStream(file);


   BufferedReader r = new BufferedReader(new InputStreamReader(fis));


   while ((strLine = r.readLine()) != null)   {


                                  dataValue = line.split(",");


                                         String first = dataValue[1];


     String second = dataValue[2];
        }
   r.close();



Using the above code snippet user can read and write csv files below is whole function for the same.



public void generateCsvFile()
{
    try
    {

        File folder = new File(Environment.getExternalStorageDirectory()
                + "/ TestFolder ");

        boolean var = false;
        if (!folder.exists())
            var = folder.mkdir();

        System.out.println("" + var);


        String fileName = folder.toString() + "/" + "Test.csv";

//Here logic can be write to arrange required format of data
        FileWriter writer = new FileWriter(fileName);

        writer.append("DisplayName");
        writer.append(',');
        writer.append("Age");
        writer.append('\n');

        writer.append("RAM");
        writer.append(',');
        writer.append("26");
        writer.append('\n');

        writer.append("ROHAN");
        writer.append(',');
        writer.append("29");
        writer.append('\n');

        writer.flush();
        writer.close();

    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}








No comments:

Post a Comment