Modify Specified Column Values

Question

My input will be a CSV file containing values shown below:

 

action, userId, firstName, email, lastName

1,2,sample,abc@gmail.com,test

2,3,justtest,def@gmail.com,test

 

I need to read this file based on headers. For ex: if action=1 and email is null, then I need to change action to 2 or email to null or another value.

I have no idea on how to read and parse values based on headers. This is my code:

 

String csvFile = "C:\\Test.csv";

    // create BufferedReader to read csv file

    BufferedReader br;

    String line = "";

    br = new BufferedReader(new FileReader(csvFile));

    br.readLine();

    // Read the file line by line starting from the second line

    while ((line = br.readLine()) != null) {

        // Get all tokens available in line

        String[] tokens = line.split(",");

        if (tokens.length > 0) {

            for (int i = 0; i < tokens.length; i++) {

                System.out.println("All Rows ------->" + tokens[i]);

            }

        }

}

 

Print all the values in new lines like below:

 

   All Rows ------->1411184866

   All Rows ------->category

   All Rows ------->123456

   All Rows ------->Test

   All Rows ------->TestFullName

   All Rows ------->rsap@gmail.com

   All Rows ------->3423131

 

Answer

Read in the CSV file and modify values according to the specified column names. It’s simple to do this in SPL (Structured Process Language):

A

1

=file("source.csv").import@ct()

2

=A1.run(if(action==1   && email==null,(action=2,email="something")))

A1: Import source.csv.

 undefined

A2: If action value is 1, change it to 2; if email value is null, change it to some other value (here is “something”).

The SPL script can be easily embedded into Java. See How to Call an SPL Script in Java.