【问题标题】:reading csv file using scanner in java在java中使用扫描仪读取csv文件
【发布时间】:2021-03-05 09:58:05
【问题描述】:
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. int
  3. int
  4. int

并且是形式

2020-10-08,4,41,0

第一行写着

日期,欧洲,亚洲,非洲

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

【问题讨论】:

标签: java csv arraylist java.util.scanner


【解决方案1】:

您可以尝试使用 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();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多