java - 使用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();
}
解决方案
在你的 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();
}
推荐阅读
- java - Java程序反转从txt文件中读取的单词
- angular - Angular - 具有基于对象的动态 id 的可折叠行
- angular - 离子 ngFor 重复列表项
- flask - socketio 事件发生时如何提供 html 代码?
- typescript - tsconfig.json 中的“outDir”如何解决?
- microservices - 微服务断路器和发现服务模式
- java - 获取无法为连接 URL 'jdbc:mysql://127.0.0.1:3306/config in Netbeans' 创建类 '' 的 JDBC 驱动程序
- c - 在 linux C 中获取密钥状态
- apache - 如果 url 中没有子域,则重定向到 www
- python - 修改该函数之外的参数而不使用“返回”python的函数