【问题标题】:How To Get a Specific Column in a CSV File如何获取 CSV 文件中的特定列
【发布时间】:2021-06-28 20:05:50
【问题描述】:

我正在使用 Spring Integration,想知道如何通过入站文件适配器提取 CSV 文件并从文件中获取特定列。 CSV 文件结构如下所示。

Header1, Header2, Header3
Value,   Value,   Value
...       ...      ...
...       ...      ...

我需要的是从第二列(Header2)中提取所有值并读取每个值。

代码如下。

@Bean
@SuppressWarnings("unchecked")
public IntegrationFlow fileIntegrationTesting() {
    
    Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    

    
    
    return IntegrationFlows
            .from(Files.inboundAdapter(new File(inputFilePath))
                    .filter(getFileFilters())
                    .autoCreateDirectory(true) ,
                    c -> c.poller(Pollers.fixedRate(1000))
                    )
            .channel("fileInputChannel")
            .transform(Files.toStringTransformer())
            .split(s -> s.applySequence(true).delimiters(","))
            .aggregate(a -> a.releaseStrategy(g -> g.size() >= 10)
                            .expireGroupsUponCompletion(true)
                    )
            
            .handle((p, h) -> gson.toJson(new RequestPayload((Collection<String>) p)))
            .enrichHeaders(eh -> eh.async(false)
                    .header("accept", "application/json")
                    .header("contentType", "application/json")
                    )
            .handle(Http.outboundGateway("URL")
                        .httpMethod(HttpMethod.POST)
                        .expectedResponseType(String.class)
                        .extractPayload(true)
                    )
            .get();
            
}

private FileListFilter<File> getFileFilters(){
     ChainFileListFilter<File> cflf = new ChainFileListFilter<>();
     cflf.addFilter(new LastModifiedFileListFilter(30));
     cflf.addFilter(new AcceptOnceFileListFilter<>());
     cflf.addFilter(new SimplePatternFileListFilter(fileExtention));
     return cflf;
}

【问题讨论】:

    标签: spring-boot spring-integration


    【解决方案1】:

    我认为您应该使用FileSplitter,而不是FileToStringTransformer,它将整个文件加载到单个字符串中。

    然后,如果您要丢弃所有其他列,使用.handle(myColumnSelector) 将是最有效的。

    有

    @Component
    public class MyColumnSelector {
    
        @ServiceActivator
        String getCol(String in) {
            return StringUtils.delimitedListToStringArray(in)[1];
        }
    
    }
    

    (为格式错误的行添加一些保护)。

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 2011-08-11
      • 2023-03-12
      • 2019-10-14
      相关资源
      最近更新 更多