Camel bindy marshal to file创建多个标题行

时间:2016-12-14 15:37:47

标签: csv apache-camel bindy

我有以下骆驼路线:

from(inputDirectory)
  .unmarshal(jaxb)
  .process(jaxb2CSVDataProcessor)
  .split(body()) //because there is a list of CSVRecords
  .marshal(bindyCsvDataFormat)
  .to(outputDirectory); //appending to existing file using "?autoCreate=true&fileExist=Append"

我的CSV模型类我正在使用注释:

@CsvRecord(separator = ",", generateHeaderColumns = true)
...

和属性

@DataField(pos = 0)
...

我的问题是每次附加新的csv记录时都会附加标题。

是否有非脏的方法来控制它?我在这里错过了什么吗?

3 个答案:

答案 0 :(得分:1)

我做了一个工作得很好的工作,通过查询@DataField批注的列来创建标题。第一次写入文件时就会发生这种情况。我在这里写下了整个解决方案:

How to generate a Flat file with header and footer using Camel Bindy

答案 1 :(得分:0)

我最终添加了一个处理器,用于检查csv文件是否存在于“to”子句之前。在那里,我对字节数组进行操作并删除标题。

答案 2 :(得分:0)

希望这对其他人有帮助。我需要做一些类似的事情,在我第一次拆分消息之后,我想抑制标题输出。这是一个完整的类('FieldUtils' 是 apache 公共库的一部分)

package com.routes;

import java.io.OutputStream;

import org.apache.camel.Exchange;
import org.apache.camel.dataformat.bindy.BindyAbstractFactory;
import org.apache.camel.dataformat.bindy.BindyCsvFactory;
import org.apache.camel.dataformat.bindy.BindyFactory;
import org.apache.camel.dataformat.bindy.FormatFactory;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.commons.lang3.reflect.FieldUtils;

public class StreamingBindyCsvDataFormat extends BindyCsvDataFormat {

    public StreamingBindyCsvDataFormat(Class<?> type) {
        super(type);
    }

    @Override
    public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception {
        final StreamingBindyModelFactory factory = (StreamingBindyModelFactory) super.getFactory();
        final int splitIndex = exchange.getProperty(Exchange.SPLIT_INDEX, -1, int.class);
        final boolean splitComplete = exchange.getProperty(Exchange.SPLIT_COMPLETE, false, boolean.class);

        super.marshal(exchange, body, outputStream);

        if (splitIndex == 0) {
        factory.setGenerateHeaderColumnNames(false); // turn off header generate after first exchange
        } else if(splitComplete) {
        factory.setGenerateHeaderColumnNames(true); // turn on header generate when split complete
        }
    }

    @Override
    protected BindyAbstractFactory createModelFactory(FormatFactory formatFactory) throws Exception {
        BindyCsvFactory bindyCsvFactory = new StreamingBindyModelFactory(getClassType());
        bindyCsvFactory.setFormatFactory(formatFactory);
        return bindyCsvFactory;
    }

    public class StreamingBindyModelFactory extends BindyCsvFactory implements BindyFactory {

        public StreamingBindyModelFactory(Class<?> type) throws Exception {
            super(type);
        }

        public void setGenerateHeaderColumnNames(boolean generateHeaderColumnNames) throws IllegalAccessException {
            FieldUtils.writeField(this, "generateHeaderColumnNames", generateHeaderColumnNames, true);
        }

    }

}
相关问题