Search code examples
javagetter-setteropencsv

Java Setters via CSV file


I have a class file with setter and getters

private double Amount;
private Date abcDate;

public double getAmount() {
    return Amount;
}
public void setAmount(double amount) {
    Amount = amount;
}
public Date getAbcDate() {
    return abcDate;
}
public void setAbcDate(Date abcDate) {
    this.abcDate = abcDate;
}

I have a CSV file with

Amount, 1000
abcDate, 12/03/2018
PersonName, John
PersonLocation, Berlin

I would like to read the CSV file and instantiate the variable via setters. I can read the CSV file using CSVReader, Univocity, openCSV etc.

How do I compare it to the setter class and set the value?


Solution

  • If your problem is just with matching you can solve it like the following with the common-csv liberary:

    Reader in = new FileReader("path/to/file.csv");
    Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
    for (CSVRecord record : records) {
        String amount = record.get("Amount");
        String abcDate = record.get("abcDate");
    
        MyDto dto = new MyDto() // use your class name here
        dto.setAmount(amount);
        dto.setAbcDate(abcDate);
        // continue to process object -> store to collection, etc
    }