在 java 中使用扫描仪读取 csv 文件

reading csv file using scanner in java

public void readCases(String filename) throws IOException {
  records.clear();  //name of list is records

  try (Scanner input = new Scanner(new File(filename))){
    input.nextLine();

    while (input.hasNext()){
      String text = input.nextLine();
      String[] element = text.split(",");
      for(int i = 0; i<=3; i++){
        if(element[i].equals(' ')){
          throw new DatasetException("column missing in csv");
        }
      }

      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
      LocalDate date = LocalDate.parse(element[0], formatter);
      int europeCases = Integer.parseInt(element[1]);
      int asiaCases = Integer.parseInt(element[2]);
      int africaCases = Integer.parseInt(element[3]);

      CaseRecord caseRecord = new CaseRecord(date, europeCases, asiaCases, africaCases);
      addRecord(caseRecord);    //this adds caseRecords to records
    }
  }
}

我正在尝试清除旧列表,然后尝试读取 CSV 文件并将列表加载到列表中。我不确定我哪里出错了。 该列表包含 4 个类型为

的字段
  1. 日期时间
  2. 整数
  3. 整数
  4. 整数

形式为

2020-10-08,4,41,0

顶行显示

Date,Europe,Asia,Africa

我想在将数据加载到列表中时跳过第一行。

您可以尝试 Java lambda 读取文件行,skip(1) 跳过第一行

        //read file into stream, try-with-resources
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

            stream.skip(1).forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }