Question

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?

Was it helpful?

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.

OTHER TIPS

Use OpenCSV for reading the file. When reading the first line store the order of the columns. When reading the following lines (which gives you one String[] per line) get the element from the array by using the information from the first line.

This is an example from the OpenCSV documentation:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    // nextLine[] is an array of values from the line
    System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

Super CSV, another open source CSV API for Java, supports this functionality out of the box. See the example on partial reading.

It uses the header (i.e. first row) to determine what fields to map to the bean - so will be able to read both of your files fine.

If you were using other types in your bean (dates, integers, etc) instead of just Strings, then Super CSV can do all the required conversions/transformations for you with it's cell processor API.

For example, the following code would read both of your files, but only populate the fields that exist in the CSV file.

ICsvBeanReader beanReader = null;
try {
        beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), 
                CsvPreference.STANDARD_PREFERENCE);

        // header is used to map CSV column -> field in bean
        final String[] header = beanReader.getHeader(true); 

        Data data;
        while( (data = beanReader.read(Data.class, header)) != null ) {
                System.out.println(String.format("id=%s, name=%s, phone=%s",
                        data.getId(), data.getName(), data.getPhone()));
        }

}
finally {
        if( beanReader != null ) {
                beanReader.close();
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top