【问题标题】:How to count number of columns in CSV using Apache Commons CSV?如何使用 Apache Commons CSV 计算 CSV 中的列数?
【发布时间】:2016-10-15 18:34:15
【问题描述】:

如何使用 Apache Commons CSV 计算 CSV 文件中的列数?我的目标是为 CSVParser 生成标题,只要我能确定列数。

CSV 文件示例:

0,1,0
1,2,3
2,3,4
...

在这种情况下,列数将为三。所以我正在寻找的是这样的:

CSVParser parser = format.parse(file);
CSVRecord firstRecord = parser.iterator().next();
int numColumns = firstRecord.size();



注意:我似乎能够很好地解析文件,只要它们在开头有一个额外的行并且我创建了一个格式,如下所示:

文件:

asdf
0,1,0
1,2,3
2,3,4
...

格式:

CSVFormat = format.withFirstRecordAsHeader().withSkipHeaderRecord()

【问题讨论】:

    标签: csv header apache-commons


    【解决方案1】:

    现在回答太晚了,不确定您使用的是什么版本。 在 Apache commonCSV 1.4 (JDK 6+) 中,firstRecord.size() 可用。

    【讨论】:

    • 我确实找到了答案,只是忘记发布了。上面回答。使用 firstRecord.size() 的问题是,commons CSV 在标题列太多或太少时拒绝文件,并且绝对需要标题。
    【解决方案2】:

    我找到的解决方案是在文件内容之前添加一个假行,并使用一种格式可以忽略标题记录。

    public static CSVParser getParserForUnknownCSV(FileInputStream inputStream)
    {
        Byte[] fakeLine = ("fake line" + System.lineSeparator()).toByteArray();
        ByteArrayInputStream fakeLineStream = new ByteArrayInputStream(fakeLine);
        SequenceInputStream prependedStream = new SequenceInputStream(fakeLineStream, inputStream);
        InputStreamReader prependedReader = new InputStreamReader(prependedStream)
    
        CSVFormat formatWithFakeHeader = CSVFormat.DEFAULT
            .withSkipHeaderRecord()
            .withHeader("fake header")
            .withAllowMissingColumnNames();
        CSVParser parser = new CSVParser(prependedReader, formatWithFameHeader);
    
        return parser;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 2018-04-22
      相关资源
      最近更新 更多