java - 在java中解析逗号分隔的数据

标签 java csv

在调用构造函数创建对象之前,我需要将输入数据解析为 4 个不同的参数,如下所示的格式。有什么想法吗?

示例数据输入格式:

rawdata = "900,300,Ernest,Fuller\n777,555,Henry,Miller\n";     //and so on

.

class BaseRecord {

      int callerId;
      int areaId;
      String firstName;
      String lastName;

      BaseRecord (int cId, int aId, String fName, String lName)

                callerId = cId;
                areaId = aId;
                firstName = fName;
                lastName = lName;

}

最佳答案

使用 java.util.regex 包中的 Matcher:

String rawdata = "900,300,Ernest,Fuller\n777,555,Henry,Miller\n";

Matcher m = Pattern.compile("(\\d+),(\\d+),(\\w+),(\\w+)", Pattern.DOTALL).matcher(rawdata);
while(m.find()){
    int cId = Integer.parseInt(m.group(1));
    int aId = Integer.parseInt(m.group(2));
    String fName = m.group(3);
    String lName = m.group(4);

    // your logic here
    new BaseRecord (int cId, int aId, String fName, String lName);
}

这样你就可以有多个换行符并防止 parseInt 上的 NumberFormatException

关于java - 在java中解析逗号分隔的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25455574/

相关文章:

java - 如何使用 Web 登录页面凭据验证 REST Web 服务调用

java - 通过NAT的P2P即时通讯

node.js - 将 CSV 转换为充满数字数组的 JSON 对象

python - 如何在 Python 中解析混合 CSV 文件?

python - 解析单个 CSV 字符串?

java - 用Java读取纯文本文件

java - JAXB 如何在解码中强制执行特定顺序

java - 无法减少 int 变量的值

csv - AWK:将困惑的记录转换为标题大小写

Python:将 URL 数据发送到 csv 阅读器