xiphias
xiphias

Reputation: 37

Parsing csv file to class getter methods with opencsv

I am trying to pass a csv file using opencsv.The csv file has three columns (,). How do i parse each line to my arraylist with the respective values? See code below.

public class Customer { 

    private String accNum;  
    private String fName;   
    private String lName;   

    public Customer(String accNum, String fName, String lName) {        

    this.accNum = accNum;
    this.fName = fName;
    this.lName = lName;
     }

    //getters & setters
    ...
}

public class CustomerList{

public void getCustList(File file) throws IOException {     
    List <Customer> custList = new ArrayList <Customer>();
    CSVReader reader = new CSVReader (new FileReader (file));
    String [] header = reader.readNext();       
    List<String[]> cList = reader.readAll();

    for (int i =0 ; i < cList.size(); i++)
    {
        String[] line = cList.get(i); //not sure how to do this
        for (String list: line)
        {
            custList.add( new Customer (list));// constructor takes three arguments
        }
    }
}

Upvotes: 1

Views: 2761

Answers (2)

John Watts
John Watts

Reputation: 8875

It's kinda like a JDBC ResultSet.

List <Customer> custList = new ArrayList <Customer>();
CSVReader reader = new CSVReader (new FileReader (file));
String[] header = reader.readNext();
if (header == null)
{
    throw new RuntimeException("No header");
}

String[] row;
while ((row = reader.readNext()) != null)
{
    if (row.length != 3) {
        throw new RuntimeException("Unexpected number of entries: " + row.length);
    }
    custList.add(new Customer(row[0], row[1], row[2]));
}

Upvotes: 1

Michael
Michael

Reputation: 1239

I would modify the for loop into something like this

for(int i = 0; i < cList.size(); i++) {
    String[] line = cList.get(i);
    custList.add(new Customer(line[0], line[1], line[2]));
}

Assuming, of course, that the columns are in the order accNum, fName, lName.

Upvotes: 1

Related Questions