Java通过CSV文件设置器

huangapple go评论67阅读模式
英文:

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(&quot;path/to/file.csv&quot;);
Iterable&lt;CSVRecord&gt; records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
    String amount = record.get(&quot;Amount&quot;);
    String abcDate = record.get(&quot;abcDate&quot;);

    MyDto dto = new MyDto() // use your class name here
    dto.setAmount(amount);
    dto.setAbcDate(abcDate);
    // continue to process object -&gt; store to collection, etc
}

huangapple
  • 本文由 发表于 2020年4月6日 22:13:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/61061816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定