簡體   English   中英

一次讀取一行 CSV 文件,然后在循環內將每一行解析為 Class 字段,然后將該 Class Z4970317944151AC3524B 存儲到數組中

[英]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 文件,然后在循環中將每一行解析為 Class 字段,然后將 Class Z49724317944151ACB355 存儲到數組中。

java class 看起來像這樣。

class 主要{

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());
        }

“CSV”可能意味着很多不同的東西,但我假設您的 CSV 文件相當簡單:

Avalue1, Bvalue1
Avalue2, Bvalue2
Avalue3, Bvalue3
  etc.

這是您如何將其解析為Main對象List的方法:

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;
}

考慮使用庫(可以處理引用字段中的逗號),例如https://commons.apache.org/proper/commons-csv/user-guide.ZFC35FDC70D5FC69D2698E83A8

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");
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM