【问题标题】:Read a CSV file one line at a time and then within the loop parse each line into the Class fields and then store that Class Object into an array一次读取一行 CSV 文件,然后在循环中将每一行解析为类字段,然后将该类对象存储到一个数组中
【发布时间】:2021-03-24 08:00:09
【问题描述】:

我想一次读取一行 CSV 文件,然后在循环中将每一行解析为 Class 字段,然后将该 Class Object 存储到一个数组中。

java 类如下所示。

主类{

String a;
String b;

public String getA() {
    return a;
}
public void setA(String a) {
    this.a = a;
}
public String getB() {
    return b;
}
public void setB(String b) {
    this.b = b;
}

public Main(String a, String b) {
    super();
    this.a = a;
    this.b = b;
}

}

我已经写了这段代码。

Scanner inFile1 = new Scanner(new File("C:\\Users\\souravpal\\Documents\\Bandicam\\a.csv"));
        Main us = new USCrimeClass();
        StringBuilder sb = new Main();
        while(inFile1.hasNext()) {
            String line = inFile1.nextLine();
            String elements[] = line.split(",");
            us.setProcess(elements[0],elements[1],elements[5],elements[9]);
            System.out.println(us.toString());
        }

【问题讨论】:

  • 为什么你认为你的方法是错误的?
  • @Kevin Anderson,你能帮忙解决这个问题吗
  • 您已经有了看起来完全合理的解决方案。它有什么问题?
  • 实际上,我必须对每个字段进行排序。先生,我怎样才能在我的代码中实现它?
  • 对每个字段进行排序?我假设您的意思是“按 A 和/或 B 字段对 Main 对象(一旦创建)进行排序”,是吗?

标签: java arrays file


【解决方案1】:

“CSV”可能意味着很多不同的东西,但我假设您的 CSV 文件相当简单:

Avalue1, Bvalue1
Avalue2, Bvalue2
Avalue3, Bvalue3
  etc.

以下是如何将其解析为 ListMain 对象:

List<Main> loadCSV(String filename) {
    List<Main> result = new ArrayList<>();
    try (BufferedReader br = new BufferedReader(new FileInputStream(filename)))
    {
        String line;
        while ((line = br.readLine()) != null) {
            String[] cols = line.split("\\s*,\\s*");
            result.add(new Main(cols[0], cols[1]);
        }
    } catch (Exception ex){
        ex.printStackTrace(System.err);
    }
    return result;
}

【讨论】:

  • 类的字段值保存后,如何获取特定列的值?
  • Main 的导入实例包含在 Kevin 提供的 loadCSV() 方法返回的列表接口中。要使用 loadCSV() 方法并从文件中导入主要对象的实例,则为:List&lt;Main&gt; list = losdCSV("C:\\YourFolder\\YourDataFile.txt");。要查看导入的主要对象实例,您可以遍历列表:for (int i = 0; i &lt; list.size(); i++) { Main instance = list.get(i); System.out.println("Object #" + (i+1) + ": --&gt; Value A: " + instance.getA() + " | Value B: " + instance.getB()); }
【解决方案2】:

考虑使用一个库(它可以处理带引号的字段中的逗号),例如 https://commons.apache.org/proper/commons-csv/user-guide.html

File infile = new File("/path/to/myfile.csv");
CSVParser parser = CSVParser.parse(infile, CSVFormat.RFC4180);
for (CSVRecord record : parser) {
    String a = record.get("A");
    String b = record.get("B");
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2010-12-11
    • 2012-07-20
    • 2023-02-10
    • 2019-01-29
    • 2015-02-01
    相关资源
    最近更新 更多