Commit 7b4cf959 authored by Riegel's avatar Riegel
Browse files

Refactor: Use try-with-resources

2 merge requests!28Version 3.17.0 Release,!26Add ZIP-archive support
Showing with 9 additions and 24 deletions
+9 -24
...@@ -36,7 +36,7 @@ public class ArchivePacker { ...@@ -36,7 +36,7 @@ public class ArchivePacker {
} }
CityDoctorModel model = entry.getModel(); CityDoctorModel model = entry.getModel();
String filename = tmpDir.toString() + File.separator + entry.getFileName(); String filename = tmpDir.toString() + File.separator + entry.getFileName();
model.saveAs(filename, entry.isValidated()); model.saveAs(filename, model.isValidated());
} }
zipDirectory(targetPath, tmpDir.toString()); zipDirectory(targetPath, tmpDir.toString());
...@@ -55,43 +55,28 @@ public class ArchivePacker { ...@@ -55,43 +55,28 @@ public class ArchivePacker {
private static void zipDirectory(String targetPath, String sourcePath){ private static void zipDirectory(String targetPath, String sourcePath){
File directory = new File(sourcePath); File directory = new File(sourcePath);
if (!directory.exists()){
throw new IllegalStateException("Directory " + sourcePath + " does not exist");
}
List<String> fileList = new ArrayList<>(Arrays.asList(directory.list())); List<String> fileList = new ArrayList<>(Arrays.asList(directory.list()));
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
FileOutputStream fos;
ZipOutputStream zos = null; try (FileOutputStream fos = new FileOutputStream(targetPath);
try { ZipOutputStream zos = new ZipOutputStream(fos)){
fos = new FileOutputStream(targetPath);
zos = new ZipOutputStream(fos);
FileInputStream in = null;
for (String file : fileList){ for (String file : fileList){
ZipEntry ze = new ZipEntry(file); ZipEntry ze = new ZipEntry(file);
zos.putNextEntry(ze); zos.putNextEntry(ze);
try { Path sourceFile = Path.of(sourcePath+File.separator+file);
Path sourceFile = Path.of(sourcePath+File.separator+file); try (FileInputStream in = new FileInputStream(sourceFile.toAbsolutePath().toString())){
in = new FileInputStream(sourceFile.toAbsolutePath().toString());
int len; int len;
while ((len = in.read(buffer)) > 0) { while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len); zos.write(buffer, 0, len);
} }
}finally {
if (in != null) {
in.close();
}
} }
} }
zos.closeEntry();
logger.info("Successfully created zip-archive"); logger.info("Successfully created zip-archive");
} catch (IOException e) { } catch (IOException e) {
logger.error(e); logger.error(e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
logger.error(e);
}
}
} }
} }
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment