骆驼Bindy @csvRecord生成页脚

时间:2018-09-25 08:02:17

标签: java csv apache-camel footer bindy

我已经使用@csvRecord用骆驼Bindy生成了CSV文件,但是无法为该csv生成页脚以显示文件中记录的总数。我可以用@FixedLenght记录生成,但不能用@csvRecord生成。请提供任何建议

1 个答案:

答案 0 :(得分:0)

您无法像使用骆驼式绑定那样通过FixedLength在CSV中生成页脚一样。

根据数据,您可以添加一条包含有关总计数等信息的附加记录。

编辑:

示例CSV文件:

FIELD1;FIELD2
test1;4
test3;6

CsvFilePojo类:

import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;

@CsvRecord(separator = ";", skipFirstLine = true)
public class CsvFilePojo {

    @DataField(pos = 1)
    private String field1;

    @DataField(pos = 2)
    private Integer field2;

    public CsvFilePojo(String field1, Integer field2) {
        this.field1 = field1;
        this.field2 = field2;
    }

    public CsvFilePojo() {
    }

    public String getField1() {
        return field1;
    }

    public void setField1(String field1) {
        this.field1 = field1;
    }

    public Integer getField2() {
        return field2;
    }

    public void setField2(Integer field2) {
        this.field2 = field2;
    }

    @Override
    public String toString() {
        return String.format("field1: %s; field2: %s", field1, field2);
    }

}

CountTotalProcessor类:

import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class CountTotalProcessor implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception {
        List<CsvFilePojo> csvlist = exchange.getIn().getBody(List.class);

        // count total
        Integer total = 0;
        for (CsvFilePojo c : csvlist) {
            total += c.getField2();
        }

        // add total as last record in csv data
        csvlist.add(new CsvFilePojo("total", total));
        exchange.getIn().setBody(csvlist);
    }
}

MyRouteBuilder类:

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;

public class MyRouteBuilder extends RouteBuilder {

    public void configure() {
        //@formatter:off
        from("file:csvFiles")
            .log("gotFile ${file:name}")
            .to("direct:processFile")
            .to("file:processedCsvFiles");

        from("direct:processFile")
            .log("processing CSV file")
            .unmarshal(new BindyCsvDataFormat(CsvFilePojo.class))
            .process(new CountTotalProcessor())
            .split(simple("${body}"))
                .log("Body ${body}")
            .end()
            ;
    }

}

使用该示例csv文件,此路由将生成如下CSV文件:

FIELD1;FIELD2
test1;4
test3;6
total;10