【问题标题】:How can I skip the first line of a csv in Java?如何在 Java 中跳过 csv 的第一行?
【发布时间】:2018-02-02 08:21:50
【问题描述】:

我想跳过第一行并使用第二行作为标题。

我正在使用 apache commons csv 中的类来处理 CSV 文件。

CSV 文件的标题位于第二行,而不是第一行(其中包含坐标)。

我的代码如下所示:

static void processFile(final File file) {
    FileReader filereader = new FileReader(file);
    final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';');
    CSVParser parser = new CSVParser(filereader, format);
    final List<CSVRecord> records = parser.getRecords();
    //stuff
}

我天真地以为,

CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(;)

会解决问题,因为它与 withFirstRowAsHeader 不同,我认为它会检测到第一行不包含任何分号并且不是记录。它没有。我试图用

跳过第一行(CSVFormat 似乎认为是标题)
CSVFormat format = CSVFormat.DEFAULT.withSkipHeaderRecord().withFirstRecordAsHeader().withDelimiter(;);

但这也行不通。我能做些什么? withFirstRowAsHeader 和 withFirstRecordAsHeader 有什么区别?

【问题讨论】:

  • 在将 fileReader 提供给解析器之前,您是否尝试过读取直到 newLine?

标签: java csv apache-commons-csv


【解决方案1】:

如果是标题,则跳过第一行的正确方法是使用不同的CSVFormat

CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';').withFirstRecordAsHeader();

【讨论】:

  • +1 for withFirstRecordAsHeader(),我将它与 CSVParser 一起使用,当您遍历解析器时它会跳过标题。
  • 这应该是公认的答案,因为它使用库,而不是临时纯 Java 解决方案
  • 这应该是公认的答案。谢谢
  • 我认为最初的问题是关于前 行,其中第二行包含标题。
【解决方案2】:

在将阅读器传递给CSVParser 之前,您可能需要阅读第一行:

static void processFile(final File file) {
    FileReader filereader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(filereader);
    bufferedReader.readLine();// try-catch omitted
    final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';');
    CSVParser parser = new CSVParser(bufferedReader, format);
    final List<CSVRecord> records = parser.getRecords();
    //stuff
}

【讨论】:

  • 如果是我的, 分隔的csv 文件,我需要将CSVFormat.DEFAULT.withDelimiter(';'); 更改为CSVFormat.DEFAULT.withDelimiter(',');。这是正确的吗?
【解决方案3】:

在 org.apache.commons:commons-csv 的 1.9.0 版本中使用:

val format = CSVFormat.Builder.create(CSVFormat.DEFAULT)
        .setHeader()
        .setSkipHeaderRecord(true)
        .build()

val parser = CSVParser.parse(reader, format)

【讨论】:

  • 或:CSVFormat.DEFAULT.builder()...
【解决方案4】:

您可以使用流跳过第一条记录:

List<CSVRecord> noHeadersLine = records.stream.skip(1).collect(toList());

【讨论】:

    【解决方案5】:

    您可以使用 Java Streams 对其进行过滤:

    parser.getRecords().stream()
         .filter(record -> record.getRecordNumber() != 1) 
         .collect(Collectors.toList());
    

    【讨论】:

    • 你能解释一下你的代码吗? csvRecordToPayerCodeMapping 需要什么?
    • 对不起,仅供内部使用,您可以跳过.map()。将编辑相同
    【解决方案6】:

    您可以使用第一行,然后将其传递给 CSVParser。除此之外还有一种方法#withIgnoreEmptyLines 可以解决这个问题。

    【讨论】:

    • 问题是行不是空的。但是使用 BufferedReader(它有一个 readLine 方法)解决了它。
    猜你喜欢
    • 2016-09-29
    • 2018-03-09
    • 2015-09-18
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多