Мне нужно создать определенную структуру папок и zip во время выполнения записывающей части моего весеннего пакетного задания.
Для этого у меня есть простой шаг с ItemReader, который читает DTO из базы данных, иItemWriter, который создает папки и архивирует в них pdf на основе текущего DTO для записи.
Проблема в том, что иногда мне нужно записать несколько pdf в один и тот же zip, но я не знаю, что в то времяписатель выполняет (это зависит от каждого элемента в списке, а не от одного элемента)
Как я могу справиться с закрытием файла в этой ситуации?
Вот соответствующая часть того, что у меня до сих пор(не обрабатывает несколько файлов в zip-файле)
public class ThirdCountriesBulletinItemWriter implements ItemWriter<ThirdCountriesDocumentDTO> {
private static final Logger LOGGER = LoggerFactory.getLogger(ThirdCountriesBulletinItemWriter.class);
private static final SimpleDateFormat MONTH_AND_YEAR_FORMAT = new SimpleDateFormat("yyyyMM");
private static final SimpleDateFormat FULL_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
private FileOutputStream fos;
private ZipOutputStream zos;
@Value("${third.countries.notif.out.location}")
protected String outputLocation;
protected File targetFolder;
@PostConstruct
public void initialize(){
targetFolder = new File(outputLocation);
}
@Override
public void write(List<? extends ThirdCountriesDocumentDTO> items){
ThirdCountriesDocumentDTO dto = items.get(0);
try{
if(!targetFolder.exists()){
LOGGER.info("Creating main directory");
setFilePermissions(targetFolder);
targetFolder.mkdir();
}
String formattedMonth = targetFolder + File.separator + MONTH_AND_YEAR_FORMAT.format(dto.getDocumentCreationDate());
File monthFolder = new File(formattedMonth);
if(!monthFolder.exists()){
LOGGER.debug("Creating month folder " + MONTH_AND_YEAR_FORMAT.format(dto.getDocumentCreationDate()) + " for country " + dto.getDossierNationality());
setFilePermissions(monthFolder);
monthFolder.mkdir();
}
fos = new FileOutputStream(monthFolder + File.separator + dto.getDossierNationality() + "-" + MONTH_AND_YEAR_FORMAT.format(dto.getDocumentCreationDate()) + ".zip");
zos = new ZipOutputStream(fos);
ZipEntry zipEntry = new ZipEntry(dto.getDossierNationality() + "-" + MONTH_AND_YEAR_FORMAT.format(dto.getDocumentCreationDate()));
String pdfName = generatePdfName(dto);
zos.putNextEntry(zipEntry);
LOGGER.debug("Writing pdf with name : " + pdfName);
zos.write(dto.getDocument());
zos.closeEntry();
}
catch (IOException e){
throw new SystemException("Error performing third country batch : " , e);
}
finally {
if(zos != null) IOUtils.closeQuietly(zos);
if(fos != null) IOUtils.closeQuietly(fos);
}
}
}
Примечание: я использую Java 6