英文:
Java Setters via CSV file
问题
我有一个包含设置器和获取器的类文件
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;
}
我有一个CSV文件,其中包含
Amount, 1000
abcDate, 12/03/2018
PersonName, John
PersonLocation, Berlin
我想要读取CSV文件,并通过设置器实例化变量。我可以使用CSVReader、Univocity、openCSV等方法读取CSV文件。
我该如何将其与设置器类进行比较并设置值?
英文:
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?
答案1
得分: 1
如果您的问题仅涉及匹配,您可以使用以下方法解决,使用common-csv库:
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(); // 在此处使用您的类名
dto.setAmount(amount);
dto.setAbcDate(abcDate);
// 继续处理对象 -> 存储到集合等
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论