首页 > 解决方案 > 使用spring集成dsl逐行读取文件

问题描述

我正在尝试读取文件,但我需要使用 Spring Integration DSL 逐行拆分它。我需要添加到我的集成流程中以使其正常工作

消息来源

 @Bean
    public MessageSource<File> sourceDirectory() {
        FileReadingMessageSource messageSource = new FileReadingMessageSource();
        messageSource.setDirectory(new File(fileSource));
        return messageSource;
    }

筛选

@Bean
    public GenericSelector<File> onlyCSVs() {
        return (file) -> file.getName().endsWith(".csv");
    }

文件转换器

 @Bean
    public FileToStringTransformer fileToStringTransformer() {
        return new FileToStringTransformer();
    }

集成流程

@Bean
    public StandardIntegrationFlow integrationFlow() {
        return IntegrationFlows
                .from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000)))
                .channel("fileInputChannel")

                .filter(onlyCSVs())
                .transform(fileToStringTransformer())
                .handle(m -> System.out.println((String.valueOf(Math.random()) + m.getPayload())))
                .get();
    }

标签: javaspring-integration-dslspring-dsl

解决方案


在你的 filetoString 转换器之后,我会添加另一个自定义转换器,它接收字符串并创建一个像这样的数组。

String.split("[\\r\\n]+")

它已经删除了空行,然后,我将在流程中添加一个 .split() 以便它为每一行创建一条消息, .split() 已经与迭代器一起使用,以防只是将数组转换为列表而你'重做。

它是这样的:

@Bean
public StandardIntegrationFlow integrationFlow() {
    return IntegrationFlows
            .from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000)))
            .channel("fileInputChannel")

            .filter(onlyCSVs())
            .transform(fileToStringTransformer())
            .transform(GenericMessage.class, message -> message.getPayload().split("[\\r\\n]+"))
            .split()
            .handle(m -> System.out.println((String.valueOf(Math.random()) + m.getPayload())))
            .get();
}

推荐阅读