From 7b4cf959f49ba360103768d942288d89573296c7 Mon Sep 17 00:00:00 2001 From: Riegel <alexander.riegel@hft-stuttgart.de> Date: Tue, 10 Dec 2024 13:31:25 +0100 Subject: [PATCH] Refactor: Use try-with-resources --- .../citydoctor2/utils/ArchivePacker.java | 33 +++++-------------- 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/CityDoctorParent/CityDoctorModel/src/main/java/de/hft/stuttgart/citydoctor2/utils/ArchivePacker.java b/CityDoctorParent/CityDoctorModel/src/main/java/de/hft/stuttgart/citydoctor2/utils/ArchivePacker.java index 947697e..b4a9967 100644 --- a/CityDoctorParent/CityDoctorModel/src/main/java/de/hft/stuttgart/citydoctor2/utils/ArchivePacker.java +++ b/CityDoctorParent/CityDoctorModel/src/main/java/de/hft/stuttgart/citydoctor2/utils/ArchivePacker.java @@ -36,7 +36,7 @@ public class ArchivePacker { } CityDoctorModel model = entry.getModel(); String filename = tmpDir.toString() + File.separator + entry.getFileName(); - model.saveAs(filename, entry.isValidated()); + model.saveAs(filename, model.isValidated()); } zipDirectory(targetPath, tmpDir.toString()); @@ -55,43 +55,28 @@ public class ArchivePacker { private static void zipDirectory(String targetPath, String 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())); - byte[] buffer = new byte[1024]; - FileOutputStream fos; - ZipOutputStream zos = null; - try { - fos = new FileOutputStream(targetPath); - zos = new ZipOutputStream(fos); - FileInputStream in = null; + + try (FileOutputStream fos = new FileOutputStream(targetPath); + ZipOutputStream zos = new ZipOutputStream(fos)){ for (String file : fileList){ ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); - try { - Path sourceFile = Path.of(sourcePath+File.separator+file); - in = new FileInputStream(sourceFile.toAbsolutePath().toString()); + Path sourceFile = Path.of(sourcePath+File.separator+file); + try (FileInputStream in = new FileInputStream(sourceFile.toAbsolutePath().toString())){ int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } - }finally { - if (in != null) { - in.close(); - } } } - zos.closeEntry(); logger.info("Successfully created zip-archive"); } catch (IOException e) { logger.error(e); - } finally { - if (zos != null) { - try { - zos.close(); - } catch (IOException e) { - logger.error(e); - } - } } } -- GitLab