簡體   English   中英

使用 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

最上面一行寫着

日期,歐洲,亞洲,非洲

我想在將數據加載到列表時跳過第一行。

您可以嘗試 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();
        }

暫無
暫無

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

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