在使用名称 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();
}
}
最佳答案
这里有几件事:
- 为什么不使用
FlatFileItemWriter
?我认为您在这里所做的事情没有什么是不能用它完成的。 - 不要对
ItemWriter
使用Closable
。 Spring Batch 具有打开和关闭资源的生命周期。它是ItemStream
接口(interface)。您可以在此处的文档中阅读有关它的更多信息:https://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/item/ItemStream.html - 您的
PrintWriter
未配置为自动刷新(默认情况下为 false)。您需要启用该功能(以便您的 writer 在每行之后刷新)或在 write 方法末尾显式调用 writer.flush() 。
关于java - Spring Batch - 自定义项目编写器未写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50288824/