Skip to content
This repository was archived by the owner on Jan 22, 2019. It is now read-only.
This repository was archived by the owner on Jan 22, 2019. It is now read-only.

Write out headers even if no data rows written #128

Closed
@ansell

Description

@ansell

If a schema is setup for a CSV writer and headers are setup to be used, the headers should be written when the writer is closed even if no data rows have been written.

Currently (unless I am using the library incorrectly), the header line is not written out unless there is at least one data row written out. I am not sure if this is relevant here or in another issue tracker such as databind.

My test code that I have been using to verify is:

List<String> headers = Arrays.asList("TestHeader1", "TestHeader2");
List<List<String>> dataSource = Arrays.asList();
// Or alternatively,
// List<List<String>> dataSource = Arrays.asList(Arrays.asList("TestValue1", "TestValue2"));
java.io.Writer writer = new StringWriter();
CsvSchema.Builder builder = CsvSchema.builder();
for (String nextHeader : headers) {
    builder = builder.addColumn(nextHeader);
}
CsvSchema schema = builder.setUseHeader(true).build();
try(SequenceWriter csvWriter = new CsvMapper().writerWithDefaultPrettyPrinter().with(schema).forType(List.class).writeValues(writer);) {
    for(List<String> nextRow : dataSource) {
        csvWriter.write(nextRow);
    }
    // Check to see whether dataSource is empty 
    // and if so write a single empty list to trigger header output
    if(dataSource.isEmpty()) {
        csvWriter.write(Arrays.asList());
    }
}
System.out.println(writer.toString());

If dataSource contains a single row, there are two lines sent to the Writer, but if it contains zero rows (as happens sometimes), I would like one line to be sent to the writer. One way as shown above is to send an empty List if we know that nothing was sent, but it would be simpler to use if that check were done internally by Jackson if it fits within the architecture.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions