0

How do I count the number of columns in a CSV file using Apache Commons CSV? My goal is to generate headers for the CSVParser, so long as I can determine the number of columns.

Example CSV file:

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

In this case the number of columns would be three. So what I'm looking for is something like:

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



Note: I seem to be able to parse files just fine as long as they have an extra line at the beginning and I create a format, as such:

file:

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

format:

CSVFormat = format.withFirstRecordAsHeader().withSkipHeaderRecord()
Gladclef
  • 687
  • 1
  • 8
  • 17

2 Answers2

3

This is too late to answer & not sure on what version you are using. With Apache commonCSV 1.4 (JDK 6+), firstRecord.size() is available.

Saurabhcdt
  • 1,010
  • 1
  • 12
  • 24
  • I actually did find an answer and just forgot to post it. Answer above. The problem with using firstRecord.size() is that commons CSV rejects the file when the header has too many columns or too few, and absolutely requires a header. – Gladclef Jan 08 '17 at 02:49
0

The solution I have found is to prepend a fake line before the contents of the file and use a format that slips the header record.

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;
}
Gladclef
  • 687
  • 1
  • 8
  • 17