java - Spring Batch - 自定义项目编写器未写入文件

标签 java spring-batch

在使用名称 ReportDetail 创建的批处理文件末尾,但该文件中没有任何内容

public class ReportWriter implements ItemWriter<Record>,Closeable {

    private PrintWriter writer = null;

    public ReportWriter() {
        OutputStream out;
        try {
            out = new FileOutputStream("ReportDetail.txt");
        } catch (FileNotFoundException e) {
            System.out.println("Exception e" + e);
            out = System.out;
        }
        try {
            this.writer = new PrintWriter(out);
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println(""+e);
        }
    }

    @Override
    public void write(final List<? extends Record> items) throws Exception {
        for (Record item : items) {
            System.out.println("item.getCode()"); // this Prints the Code
            writer.println(item.getCode()); // Not Working
        }
    }

    @PreDestroy
    @Override
    public void close() throws IOException {
        writer.close();
    }
}

最佳答案

这里有几件事:

  1. 为什么不使用FlatFileItemWriter?我认为您在这里所做的事情没有什么是不能用它完成的。
  2. 不要对 ItemWriter 使用 Closable。 Spring Batch 具有打开和关闭资源的生命周期。它是 ItemStream 接口(interface)。您可以在此处的文档中阅读有关它的更多信息:https://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/item/ItemStream.html
  3. 您的 PrintWriter 未配置为自动刷新(默认情况下为 false)。您需要启用该功能(以便您的 writer 在每行之后刷新)或在 write 方法末尾显式调用 writer.flush() 。

关于java - Spring Batch - 自定义项目编写器未写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50288824/

相关文章:

java - 非法选项: -ext Try keytool

java - 覆盖 AWT 并存储图形

java - Spring - 使用存储过程时使用 simplejdbccall 进行批量更新

java - Spring 批处理 : How do I return custom exit code on invalid record with exception in spring batch

spring - java - 如何为spring批处理数据和业务数据配置单独的数据源?我应该这样做吗?

java - 在 MongoDB 中将日期作为字符串进行比较

java - AEM/CQ5 多个 bundle 相同的包名称和不同的数据类型属性

java - XML在Java中编辑所有同名标签

java - 处理多个 StoredProcedureItemReader 调用

java - 在 Spring Batch 项目中实现 ItemReader 时如何打开 Reader?