gpt4 book ai didi

java - 使用 opencsv 将 csv 文件解析为类 getter 方法

转载 作者:行者123 更新时间:2023-11-30 04:45:53 31 4
gpt4 key购买 nike

我正在尝试使用 opencsv 传递 csv 文件。csv 文件有三列 (,)。如何使用相应的值将每一行解析到数组列表中?请参阅下面的代码。

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
}
}
}

最佳答案

它有点像 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]));
}

关于java - 使用 opencsv 将 csv 文件解析为类 getter 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10964975/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com