【问题标题】:Append to CSV file with header in Apache Camel在 Apache Camel 中附加到带有标题的 CSV 文件
【发布时间】:2020-11-12 21:05:10
【问题描述】:

我需要根据传入的消息构建一个 csv 文件。我通过附加到文件来做到这一点:

.toD("file://" + OUTPUT_PATH + "?FileName=${exchangeProperty.OUTPUT_FILENAME}" + "&FileExist=Append")

虽然这很好用,但我遇到了一个问题。我还需要在 CSV 文件中包含一个标题行。现在我正在使用 .mashall().csv() 编组为 CSV 格式,但这省略了标题。

虽然我可以创建带有标题的 CSV 格式:

CsvDataFormat csvFormatWithHeader = new CsvDataFormat();
csvFormatWithHeader.setHeader(Arrays.asList(new String[] { "A", "B", "C", "D" }.clone()));

.marshall(csvFormatWithHeader)

这将为我添加的每一行添加标题行。 所以我想要实现的是仅在创建新文件时添加标题。

我一直在尝试两种方法,但都没有奏效:

  1. 检查路径中是否存在文件并相应地应用 csv 格式
  2. 使用 bean 或方法设置 marshall 数据格式

作为最后的选择,我可以在文件关闭时添加标题,但感觉效率低下,因为我不知道该文件可能会变得多大。

如何使用 Apache Camel 2.23.2 实现这两种方法。

【问题讨论】:

    标签: csv apache-camel


    【解决方案1】:

    好的,最终使用标题我能够让选项 1 起作用。这是我的路线现在的样子:

    .setProperty("OUTPUT_FILENAME",method(this, "determineOutputFilename()"))
    .setHeader("fileExists", method(this, "outputFileExists"))
    .choice()
      .when(header("fileExists"))
        .marshal().csv()
      .endChoice()
      .otherwise()
        .marshal(csvFormatWithHeader)
      .endChoice()
    .end()
    

    文件检查逻辑是(在路由类中实现):

    public boolean outputFileExists(@ExchangeProperty("OUTPUT_FILENAME") String fileName){
        boolean fileExists = new File(PROCESSING_PATH + "/" + fileName).exists();
        return fileExists;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2021-01-04
      • 2018-11-18
      • 1970-01-01
      • 2021-10-06
      • 2021-02-19
      相关资源
      最近更新 更多