将CSV文件映射到POJO

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

mapping CSV file to POJO

问题

NAME(姓名),MOBILE(手机号码),CITY(城市),EMAIL(电子邮件)

Alfreds,123566X,Delhi,abc@gmail.com

我有一个文件,其中只有两行,第一行是标题行,第二行是值行。
文件中只有两个字段是固定的,即NAME(姓名)和MOBILE(手机号码),其他字段不固定,例如文件可能是(NAME, MOBILE, PRODUCT)或(NAME, MOBILE, SUMMARY, ABC, XYZ)等等。

我想将这个文件映射到实体类中。

public class MyPojo {
    private String NAME;
    private int MOBILE;
    private ???  // 请填写适当的字段类型
        
    //getter和setter方法
}

任何帮助都将不胜感激。
请建议我如何做到这一点。
请帮助。提前感谢。我是编程世界的新手。

File file = new File("file.csv");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String[] line1 = br.readLine().split(",");
String[] line2 = br.readLine().split(",");
英文:

NAME,MOBILE,CITY,EMAIL

Alfreds,123566X,Delhi,abc@gmail.com

I have this file which has only two lines first is headers line second is values line.
Only two fileds are fixed in file NAME and MOBILE others are not fixed like file may be(NAME,MOBILE,PRODUCT) or may be (NAME,MOBILE,SUMMURY,ABC,XYZ) etc.

I want to map this file to entity class

public class MyPojo{
    private String NAME;
    private int MOBILE;
    private ???
    
    //getter and setter
}

Any help highly apperciated.
Suggest me any solution how can i do this.
Please help. Thanks in advance. New to programming world.

  File file=new File("file.csv");   
FileReader fr=new FileReader(file);   
BufferedReader br=new BufferedReader(fr);  
String [] line1 = br.readLine().split(",");
String [] line2 = br.readLine().split(",");

答案1

得分: 0

我会假设,出于简单回答的考虑,实际数据中没有逗号。如果你想解析更通用的CSV文件,最好使用库,如果你不确定是否完全可以从头开始完成。

你需要使用String.split方法将每个字符串按逗号分割 (https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-)。阅读文档会告诉你需要传递一个“正则表达式”作为分隔符。你可以在这里了解更多关于正则表达式的信息,但要匹配一个逗号,你可以使用字面逗号。

String header, data;
// 将文件读入上述字符串
String[] headings = header.split(",");
String[] fields   = data.split(",");

现在你需要将这些数据传递给你的类。创建一个数据的HashMap,并将其传递给Pojo的构造函数:

import java.util.HashMap;
import java.util.Map;
// Math.min选择两个值中的较小值
int nItems = Math.min(headings.length, fields.length);
Map<String,String> map = new HashMap<String,String>(nItems);
// 从第三项开始
for (int i = 2; i < nItems; i++) {
    map.put(headings[i], fields[i]);
}
Pojo pojo = new Pojo(fields[0], fields[1], map);

然后,你只需要在Pojo类上创建一个构造函数,该构造函数接受参数 (String name, String mobile, Map<String,String> extraData)

class Pojo {
    String name, mobile;
    Map<String,String> extraData;
    public Pojo(String name, String mobile, Map<String,String> extraData) {
        this.name = name;
        this.mobile = mobile;
        this.extraData = new HashMap<String,String>(extraData);
    }
    // getters/setters.....
}
英文:

I will assume, for the sake of a simple answer, that there are no commas in the actual data. If you want to parse a more general CSV file, it would be better to use a library if you lack the confidence to do it fully from scratch.

You need to split each string at the commas so use String.split (https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-). Reading the documentation tells you to pass a "regex" for the delimiter. You can read more about regexes here but to match just a comma you can use a literal comma.

String header, data;
// Read file into the above strings
String[] headings = header.split(&quot;,&quot;);
String[] fields   = data.split(&quot;,&quot;);

Now you need to feed this into your class. Create a HashMap of the data and pass it to the constructor of Pojo:

import java.util.HashMap;
import java.util.Map;
// Math.min selects the smaller of two values
int nItems = Math.min(headings.length, fields.length);
Map&lt;String,String&gt; map = new HashMap&lt;String,String&gt;(nItems);
// Start at the third item
for (int i = 2; i &lt; nItems; i++) {
    map.put(headings[i], fields[i]);
}
Pojo pojo = new Pojo(fields[0], fields[1], map);

You then just need a constructor on Pojo that takes arguments (String name, String mobile, Map&lt;String,String&gt; extraData).

class Pojo {
    String name, mobile;
    Map&lt;String,String&gt; extraData;
    public Pojo(String name, String mobile, Map&lt;String,String&gt; extraData) {
        this.name = name;
        this.mobile = mobile;
        this.extraData = new HashMap&lt;String,String&gt;(extraData);
    }
    // getters/setters....
}

</details>



huangapple
  • 本文由 发表于 2020年8月9日 05:33:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63320423.html
匿名

发表评论

匿名网友

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

确定