0

I have a csv file with input content separated with comma ",". I want to convert that into text file with "|" delimiter. I'm using apache camel CsvDataFormat to convert the given csv data format.I can be able to convert the csv content to pipe delimited string. I have two more constants which I have assigned to two variables.I would like to enrich the content of the output data with two additional fields as shown in expected output.

Input

test.csv

Jack Dalton, 115, mad at Averell 
Joe Dalton, 105, calming Joe 
William Dalton, 105, keeping Joe from killing 
Averell Averell Dalton, 80, playing with Rantanplan 
Lucky Luke, 120, capturing the Daltons

Test.java

public class Test{
    private String name = "Hell0";
    private String address = "134 johen rd";
}

ConverterRoute.java

public class ConverterRoute implements RoutesBuilder {

    private static final String SOURCE_INPUT_PATH = "file://inbox?fileName=test.csv";

    private static final String SOURCE_OUTPUT_PATH = "file://outbox?fileName=file.txt";

    public void addRoutesToCamelContext(CamelContext context) throws Exception {

        context.addRoutes(new RouteBuilder() {
            public void configure() {
                try {
                    CsvDataFormat csvDataFormat = new CsvDataFormat();
                    csvDataFormat.setDelimiter('|');
                    csvDataFormat.setHeaderDisabled(true);

                    from(SOURCE_INPUT_PATH).
                            unmarshal().csv().
                            marshal(csvDataFormat).
                            to(SOURCE_OUTPUT_PATH)
                            .end();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Output

file.txt

Jack Dalton| 115 | mad at Averell 
Joe Dalton| 105 | calming Joe
William Dalton | 105 | keeping Joe from killing
Averell Averell Dalton| 80| playing with Rantanplan
Lucky Luke| 120| capturing the Daltons

Expected Output

file.txt

Jack Dalton| 115 | mad at Averell | Hell0 | 134 johen rd
Joe Dalton| 105 | calming Joe | Hell0 | 134 johen rd
William Dalton | 105 | keeping Joe from killing | Hell0 | 134 johen rd
Averell Averell Dalton| 80| playing with Rantanplan | Hell0 | 134 johen rd
Lucky Luke| 120| capturing the Daltons | Hell0 | 134 johen rd

In the above output file.txt the last two columns are the two constants which I have in my Test.java pojo class. I would like to enrich my pojo fields into the final output. Is there a way I can achieve the result.

4

1 回答 1

1

步骤后在您的路线中

unmarshal().csv()

你有一个List<List<String>>作为消息体。外部列表的每个列表条目代表一个 CSV 行,每个内部列表包含一行的值。

您要做的是向每个内部列表添加两个值。

由于每个“行”的值都相同,因此编写一个普通的 Java Bean 可能是最简单的方法,该 BeanList<List<String>>遍历外部列表并将两个值(列表条目)添加到每个内部列表。

在您的骆驼路线中,您将此bean称为

.bean(YourBean.class, "methodname")

methodname仅在 Bean 具有多个方法时才需要。

然后你的路线继续

.marshal(csvDataFormat)
.to(SOURCE_OUTPUT_PATH)

这应该会生成您想要的文件。

顺便说一句,.end()不需要在路线的尽头。

于 2020-03-27T16:39:03.010 回答