2

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,[email protected],test
    2,3,justtest,[email protected],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 ------->[email protected]
   All Rows ------->3423131

Please help me completing this code. Thanks in advance.

1
  • Also, you could use .hasNextLine() instead of the if you currently have, that'll sinch it for the project. Very readable. Commented Oct 16, 2015 at 16:48

2 Answers 2

3

For parsing the CSV file into a post-processable format, I would first create an enum that models the columns of the file, in correct order:

enum Column {
    ACTION, USERID, FIRSTNAME, EMAIL, LASTNAME;
    public static final Column[] VALUES = values();
}

Then, I would read the file into a mapping of columns into lists of column values (this data structure is also called a "multimap"):

Map<Column, List<String>> columns = 
    new LinkedHashMap<>();
// initialize the map
for (Column c : Column.VALUES) {
    columns.put(c, new ArrayList<>());
}

String csvFile = "C:\\Test.csv";        
String line = "";
// create BufferedReader to read csv file
BufferedReader 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++) {
            columns.get(Column.VALUES[i]).add(tokens[i].trim());
        }
    }
}

Now that you have the data ordered, you can start post-processing the values based on your business rules. Of course you can also apply the rules while reading the file, but this might hurt readability of the code. Accessing individual cells in the file is easy; e.g. the email address on the second row can be retrieved using columns.get(Column.EMAIL).get(1).

Running

System.out.println(columns);

with your example file outputs this:

{ACTION=[1, 2], USERID=[2, 3], FIRSTNAME=[sample, justtest], 
 EMAIL=[[email protected], [email protected]], LASTNAME=[test, test]}
Sign up to request clarification or add additional context in comments.

Comments

2

Use Apache Common CSV libraries (or any other suitable libraries) to read the CSV files and then apply the business logic in the program.

https://commons.apache.org/proper/commons-csv/

It will give you the list of rows in the form of CSVRecord and then you just need to apply business logic based on the values by iterarting over the list. The first element in the list will be your header.

        Reader in = new FileReader("File Name");
        CSVParser parser = new CSVParser(in, CSVFormat.EXCEL);
        List<CSVRecord> csvRecords = parser.getRecords();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.