0

是否有可能获得写入的总行数FlatFileItemWriter.headerCallback()

我是一个 spring-batch nubee,我研究了将行数放入平面文件Spring Batch - Counting Processed Rows的标题中。但是,我似乎无法使用那里给出的建议来实现逻辑。有意义的是,作者计数仅在文件处理后才可用。但是,我试图在文件正式写入之前获取行数。

我试图寻找一个像钩子一样的钩子@AfterStep并抓住总行,但我一直在绕圈子。

@Bean
@StepScope
public FlatFileItemWriter<MyFile> generateMyFileWriter(Long jobId,Date eventDate) {
    String filePath = "C:\MYFILE\COMPLETED";
    Resource file = new FileSystemResource(filePath);

    DelimitedLineAggregator<MyFile> myFileLineAggregator = new DelimitedLineAggregator<>();
    myFileLineAggregator.setDelimiter(",");
    myFileLineAggregator.setFieldExtractor(getMyFileFieldExtractor());

    return new FlatFileItemWriterBuilder<MyFile>()
            .name("my-file-writer")
            .resource(file)
            .headerCallback(new MyFileHeaderWriter(file.getFilename()))
            .lineAggregator(myFileLineAggregator)
            .build();
}

private FieldExtractor<MyFile> getMyFileFieldExtractor() {
    final String[] fieldNames = new String[]{
            "typeRecord",
            "idSystem"               
    };  
    return item -> {
        BeanWrapperFieldExtractor<MyFile> extractor = new BeanWrapperFieldExtractor<>();
        extractor.setNames(fieldNames);
        return extractor.extract(item);
    };
}

请注意,我在(上)中使用MyFileHeaderWriter.java类(下headerCallback(new MyFileHeaderWriter(file.getFilename())))。我正在尝试初始化qtyRecordsCreated下面的值。

class MyFileHeaderWriter implements FlatFileHeaderCallback {

 private final String header;

 private String dtxCreated;
 private String tmxCreated;
 private String fileName;//15 byte file name    private String qtyRecordsCreated;//number of rows in file including the header row

 MyFileHeaderWriter(String sbfFileName) {
    SimpleDateFormat dateCreated = new SimpleDateFormat("YYDDD");
    SimpleDateFormat timeCreated = new SimpleDateFormat("HHMM");
    Date now = new Date(); 

    this.dtxCreated = dateCreated.format(now);
    this.tmxCreated = timeCreated.format(now);
    this.fileName = sbfFileName;        this.qtyRecordsCreated="";  

    String[] headerValues = {dtxCreated,tmxCreated,fileName,qtyRecordsCreated};
     this.header = String.join(",", headerValues);
 }

 @Override
 public void writeHeader(Writer writer) throws IOException {
     writer.write(header);
 }
}

如何获取标题行中的行数?可以FlatFileFooterCallback用来获取行数,然后用文件中的行数更新标题吗?

4

1 回答 1

0

你可以做到这一点ItemProcessor,试试这个对我有用

public class EmployeeProcessor implements ItemProcessor<Employee, Employee> {
    @Override
    public Employee process(Employee employee) throws Exception {

         return employee;
    }

     @AfterStep
    public void afterStep(StepExecution stepExecution) {
      ExecutionContext stepContext = stepExecution.getExecutionContext();
      stepContext.put("count",  stepExecution.getReadCount());
      System.out.println("COUNT" + stepExecution.getReadCount());
    }
}

在你作家中获得价值

int count = stepContext.getInt("count");

希望对你有用

于 2020-01-29T15:44:33.907 回答