简体   繁体   English

Spring 批量 FlatFileItemWriter 从 Object 写入 csv

[英]Spring batch FlatFileItemWriter write as csv from Object

I am using Spring batch and have an ItemWriter as follows:我正在使用 Spring 批处理并有一个 ItemWriter 如下:

public class MyItemWriter implements ItemWriter<Fixing> {

    private final FlatFileItemWriter<Fixing> writer;
    private final FileSystemResource resource;

    public MyItemWriter () {
        this.writer = new FlatFileItemWriter<>();
        this.resource = new FileSystemResource("target/output-teste.txt");
    }


    @Override
    public void write(List<? extends Fixing> items) throws Exception {

        this.writer.setResource(new FileSystemResource(resource.getFile()));
        this.writer.setLineAggregator(new PassThroughLineAggregator<>());
        this.writer.afterPropertiesSet();
        this.writer.open(new ExecutionContext());
        this.writer.write(items);
    }

    @AfterWrite
    private void close() {
        this.writer.close();
    }
}

When I run my spring batch job, the items are written to file as:当我运行我的 spring 批处理作业时,这些项目被写入文件:

Fixing{id='123456', source='TEST', startDate=null, endDate=null}
Fixing{id='1234567', source='TEST', startDate=null, endDate=null}
Fixing{id='1234568', source='TEST', startDate=null, endDate=null}

1/ How can I write just the data so that the values are comma separated and where it is null, it is not written. 1/我怎样才能只写数据,以便值以逗号分隔,并且它是 null,它没有被写入。 So the target file should look like this:所以目标文件应该是这样的:

123456,TEST
1234567,TEST
1234568,TEST

2/ Secondly, I am having an issue where only when I exit spring boot application, I am able to see the file get created. 2 / 其次,我有一个问题,只有当我退出 spring 启动应用程序时,我才能看到文件被创建。 What I would like is once it has processed all the items and written, the file to be available without closing the spring boot application.我想要的是,一旦它处理了所有项目并写入,文件就可以在不关闭 spring 引导应用程序的情况下使用。

There are multiple options to write the csv file.写入 csv 文件有多种选择。 Regarding second question writer flush will solve the issue.关于第二个问题 writer flush 将解决问题。

  1. https://howtodoinjava.com/spring-batch/flatfileitemwriter-write-to-csv-file/ https://howtodoinjava.com/spring-batch/flatfileitemwriter-write-to-csv-file/
  1. We prefer to use OpenCSV with spring batch as we are getting more speed and control on huge file example snippet is below我们更喜欢将 OpenCSV 与 spring 批处理一起使用,因为我们正在获得更快的速度和对大文件示例片段的控制如下

    class DocumentWriter implements ItemWriter<BaseDTO>, Closeable { private static final Logger LOG = LoggerFactory.getLogger(StatementWriter.class); private ColumnPositionMappingStrategy<Statement> strategy; private static final String[] columns = new String[] { "csvcolumn1", "csvcolumn2", "csvcolumn3", "csvcolumn4", "csvcolumn5", "csvcolumn6", "csvcolumn7"}; private BufferedWriter writer; private StatefulBeanToCsv<Statement> beanToCsv; public DocumentWriter() throws Exception { strategy = new ColumnPositionMappingStrategy<Statement>(); strategy.setType(Statement.class); strategy.setColumnMapping(columns); filename = env.getProperty("globys.statement.cdf.path")+"-"+processCount+".dat"; File cdf = new File(filename); if(cdf.exists()){ writer = Files.newBufferedWriter(Paths.get(filename), StandardCharsets.UTF_8,StandardOpenOption.APPEND); }else{ writer = Files.newBufferedWriter(Paths.get(filename), StandardCharsets.UTF_8,StandardOpenOption.CREATE_NEW); } beanToCsv = new StatefulBeanToCsvBuilder<Statement>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withMappingStrategy(strategy).withSeparator(',').build(); } @Override public void write(List<? extends BaseDTO> items) throws Exception { List<Statement> settlementList = new ArrayList<Statement>(); for (int i = 0; i < items.size(); i++) { BaseDTO baseDTO = items.get(i); settlementList.addAll(baseDTO.getStatementList()); } beanToCsv.write(settlementList); writer.flush(); } @PreDestroy @Override public void close() throws IOException { writer.close(); }

    } }

Since you are using PassThroughLineAggregator which does item.toString() for writing the object, overriding the toString() function of classes extending Fixing.java should fix it.由于您使用 PassThroughLineAggregator 执行 item.toString() 来编写 object,因此覆盖扩展 Fixing.Z93F725A07423FE1C889F448B33D2 的类的 toString() function 应该修复。

1/ How can I write just the data so that the values are comma separated and where it is null, it is not written. 1/我怎样才能只写数据,以便值以逗号分隔,并且它是 null,它没有被写入。

You need to provide a custom LineAggregator that filters out null fields.您需要提供一个自定义LineAggregator过滤掉null字段。

2/ Secondly, I am having an issue where only when I exit spring boot application, I am able to see the file get created 2 / 其次,我遇到了一个问题,只有当我退出 spring 启动应用程序时,我才能看到文件被创建

This is probably because you are calling this.writer.open in the write method which is not correct.这可能是因为您在write方法中调用this.writer.open是不正确的。 You need to make your item writer implement ItemStream and call this.writer.open and this this.writer.close respectively in ItemStream#open and ItemStream#close您需要让您的项目编写器实现ItemStream并在ItemStream#openItemStream#close中分别调用this.writer.openthis.writer.close

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Batch-FlatFileItemWriter写入文件,关闭该文件,写入新文件 - Spring Batch - FlatFileItemWriter write to a file, close it, write to new file Spring 批处理 FlatFileItemWriter - 写入后在 csv 中显示指数值 - Spring batch FlatFileItemWriter - Showing exponential value in csv after writing it 如何在Spring批处理中使用FlatFileItemWriter写入stdout? - How can I write to stdout using FlatFileItemWriter in spring batch? Spring Batch FlatFileItemWriter - 输出自定义 - Spring Batch FlatFileItemWriter - output customization 如何在使用 Spring Batch FlatFileItemWriter 写入 csv 文件时跳过空白行 - how to skip blank lines while writing to csv file with Spring Batch FlatFileItemWriter 为什么在春季批处理中不使用FlatFileItemWriter创建文件? - Why file not creating using FlatFileItemWriter in spring batch? Spring Batch:无法访问flatfileitemwriter中的jobexecutionConext - Spring Batch: not able to access jobexecutionConext in flatfileitemwriter FlatFileItemWriter在Spring批处理中在异常时生成空白文件 - FlatFileItemWriter generating blank file on exception in Spring batch 将带有列表的 object 保存为 csv 文件 FlatFileItemWriter - Save object with List as csv file FlatFileItemWriter Spring Batch FlatFileItemWriter仅在第二次运行后才处理数据 - Spring Batch FlatFileItemWriter does only process data after second run
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM