Search code examples
javacsvimportopencsvsupercsv

how to fill class from partial csv file


I have class in Java:

class data {
  private String id;
  private String name;
  private String phone;
}

and I need to fill data from CSV file. But not all columns in CSV file are mandatory, or could be in different order.

CSV Example1:

id, phone, name
1,421904123456,Peter
2,420558811225,John
...

CSV Example2:

id, name
3,Alex
8,Stefan

Any advice how to do that?


Solution

    1. Read first line to get header info.
    2. Based on header info populate a Method[] array with setters of fields read.
    3. for each subsequent row, create a object obj of Data class and for each value in row and call invoke() on all elements of array passing the newly created object and rad value as parameter.

    May be you can also look into Execute SQL on CSV files via JDBC to query CSV using jdbc.

    Also, your class should be Data instead of data.