根据列名读入数据并变换

【问题】

I have a requirement like:

1.     My input will be a csv file where I will be having values like below:

action, userId, firstName, email, lastName
1,2,sample,abc@gmail.com,test
2,3,justtest,def@gmail.com,test

2.     I have to read this csv file based on headers. Say for ex: if action =1 and email is null, then I have to change from action to 2 or email to null or something like this.

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

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]);
            }
        }
    }

This is just printing all the values in new line 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

【回答】

       按先读入csv文件再按照列名对文件内容进行处理,使用SPL来实现要简单许多:

 


A

1

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

2

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

 

A1:读取source.csv文件内容。

undefined

A2:将记录中action=1emai=null的数据修改为action=2email= something

这段代码可以方便地集成进Java,参考Java 如何调用 SPL 脚本