我使用方法编写了以下代码tasklet
来生成包含数据的文件。
public class PersonInfoFileWriter implements Tasklet {
@Autowired
PersonInfoFileUtil personInfoFileUtil;
public void write(ExecutionContext executionContext) throws IOException {
List<PersonInfo> personInfoList = null;
FlatFileItemWriter<PersonInfo> flatFileWriter = new FlatFileItemWriter<PersonInfo>();
flatFileWriter.setResource(new FileSystemResource("C:\\test\\"
+ LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + ".txt"));
try {
flatFileWriter.open(executionContext);
String personName = (String) executionContext.get("personInfo");
//gets the details of the person by name from the database and assign the values to PersonInfo
personInfoList = personInfoFileUtil.setDataForPersonInfoFile(personName);
flatFileWriter.setName("Person-Detail-File");
flatFileWriter.setShouldDeleteIfEmpty(true);
flatFileWriter.setAppendAllowed(true);
flatFileWriter.setLineSeparator("\n");
flatFileWriter.setHeaderCallback(new FlatFileHeaderCallback() {
@Override
public void writeHeader(Writer writer) throws IOException {
writer.write(
"PersonId^Name^Program^ProgramType");
}
});
flatFileWriter.setLineAggregator(new DelimitedLineAggregator<PersonInfo>() {
{
setDelimiter("^");
setFieldExtractor((FieldExtractor<PersonInfo>) new BeanWrapperFieldExtractor<PersonInfo>() {
{
setNames(new String[] { "personId", "name", "program", "programType" });
}
});
}
});
String lines = flatFileWriter.doWrite((List<? extends PersonInfo>) personInfoList);
logger.info(lines); //this prints the information correctly
} finally {
flatFileWriter.close();
}
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
ExecutionContext executionContext = contribution.getStepExecution().getJobExecution().getExecutionContext();
write(executionContext);
return RepeatStatus.FINISHED;
}
}
上面的代码编译并运行没有错误,但它没有在磁盘上生成任何文件。
我尝试调试以检查是否在缓冲区上创建了 fileName 和 etc 值以写入磁盘,并且除了生成数据并将数据写入文件之外,一切都按预期工作。
如果我使用基于块的方法编写代码,它工作正常。
如果我做错了什么,请告诉我。我在这里先向您的帮助表示感谢。
编辑:添加建议的更改后,文件正在磁盘上创建,但文件丢失了我使用 setHeaderCallback() 设置的标题