Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring批处理FlatFileItemWriter从对象以csv形式写入_Java_Spring_Spring Boot_Spring Batch - Fatal编程技术网

Java Spring批处理FlatFileItemWriter从对象以csv形式写入

Java Spring批处理FlatFileItemWriter从对象以csv形式写入,java,spring,spring-boot,spring-batch,Java,Spring,Spring Boot,Spring Batch,我使用的是Spring批处理,有一个ItemWriter,如下所示: public class MyItemWriter implements ItemWriter<Fixing> { private final FlatFileItemWriter<Fixing> writer; private final FileSystemResource resource; public MyItemWriter () { this.w

我使用的是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();
    }
}
1/如何仅写入数据,使值以逗号分隔,如果为空,则不写入。因此,目标文件应如下所示:

123456,TEST
1234567,TEST
1234568,TEST

2/其次,我遇到了一个问题,只有当我退出spring启动应用程序时,我才能看到创建的文件。我想要的是,一旦它处理完所有项目并写入,该文件就可以在不关闭spring boot应用程序的情况下使用。

有多个选项可以写入csv文件。关于第二个问题,作者flush将解决这个问题

  • 我们更喜欢将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();
    
           }
    
    类DocumentWriter实现ItemWriter,可关闭{ 私有静态最终记录器LOG=LoggerFactory.getLogger(StatementWriter.class); 私人专栏;战略; 私有静态最终字符串[]列=新字符串[]{“csvcolumn1”、“csvcolumn2”、“csvcolumn3”, “CSV列4”、“CSV列5”、“CSV列6”、“CSV列7”}; 私有缓冲写入程序; 私有状态Beantocv Beantocv; public DocumentWriter()引发异常{ 策略=新列位置映射策略(); strategy.setType(Statement.class); 策略.setColumnMapping(列); filename=env.getProperty(“globys.statement.cdf.path”)+“-”+processCount+“.dat”; 文件cdf=新文件(文件名); if(cdf.exists()){ writer=Files.newBufferedWriter(path.get(文件名)、StandardCharsets.UTF_8、StandardOpenOption.APPEND); }否则{ writer=Files.newBufferedWriter(path.get(文件名)、StandardCharsets.UTF_8、StandardOpenOption.CREATE_NEW); } beanToCsv=新状态BEANTOCSVBuilder(writer)。带引号(CSVWriter.NO“u QUOTE”字符) .withMappingStrategy(strategy)。withSeparator(',).build(); } @凌驾
    public void write(List有多个选项可以写入csv文件。关于第二个问题,writer flush将解决该问题

  • 我们更喜欢将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();
    
           }
    
    类DocumentWriter实现ItemWriter,可关闭{ 私有静态最终记录器LOG=LoggerFactory.getLogger(StatementWriter.class); 私人专栏;战略; 私有静态最终字符串[]列=新字符串[]{“csvcolumn1”、“csvcolumn2”、“csvcolumn3”, “CSV列4”、“CSV列5”、“CSV列6”、“CSV列7”}; 私有缓冲写入程序; 私有状态Beantocv Beantocv; public DocumentWriter()引发异常{ 策略=新列位置映射策略(); strategy.setType(Statement.class); 策略.setColumnMapping(列); filename=env.getProperty(“globys.statement.cdf.path”)+“-”+processCount+“.dat”; 文件cdf=新文件(文件名); if(cdf.exists()){ writer=Files.newBufferedWriter(path.get(文件名)、StandardCharsets.UTF_8、StandardOpenOption.APPEND); }否则{ writer=Files.newBufferedWriter(path.get(文件名)、StandardCharsets.UTF_8、StandardOpenOption.CREATE_NEW); } beanToCsv=新状态BEANTOCSVBuilder(writer)。带引号(CSVWriter.NO“u QUOTE”字符) .withMappingStrategy(strategy)。withSeparator(',).build(); } @凌驾
    public void write(List因为您使用的是PassThroughLineAggregator,它执行item.toString()来写入对象,重写扩展Fixing.java的类的toString()函数应该可以修复它。

    因为您使用的是PassThroughLineAggregator,它执行item.toString()来写入对象,所以重写toString()扩展Fixing.java的类的函数应该修复它

    1/如何仅写入数据,使值以逗号分隔,如果为空,则不写入

    您需要提供一个自定义的
    LineAggregator
    ,它过滤掉
    null
    字段

    2/其次,我遇到了一个问题,只有当我退出spring启动应用程序时,我才能看到创建的文件

    这可能是因为您在
    write
    方法中调用
    This.writer.open
    不正确。您需要让项目编写器实现
    ItemStream
    并分别在
    ItemStream\open
    ItemStream\close中调用
    This.writer.open
    This
    This.writer.close

    1/如何仅写入数据,使值以逗号分隔,如果为空,则不写入

    您需要提供一个自定义的
    LineAggregator
    ,它过滤掉
    null
    字段

    2/其次,我遇到了一个问题,只有当我退出spring启动应用程序时,我才能看到创建的文件


    这可能是因为您在
    write
    方法中调用
    This.writer.open
    不正确。您需要让项目编写器实现
    ItemStream
    并分别在
    ItemStream\open
    ItemStream\close中调用
    This.writer.open
    This
    This.writer.close

    对于1/我使用了一个
    NullSafeBeanWrapperFieldExtractor
    。对于2/,我进行了更改以实现ItemStream,但在我开始在我的writer上使用
    @Configuration
    时,这个问题已经得到了解决,而以前它没有得到解决